#!/bin/bash
# Airspine hotspot bootstrap, stage 1. Holds no secrets of its own.
#
# Asks for the access password and sends it to the server over the same
# pinned TLS. Only if the server accepts it does the real script (stage 2,
# which carries this site's tunnel key) come back. Five wrong passwords and
# the server destroys the link.

main() {
    local url='https://setup.airspine.au/unlock' pw resp code body=""
    # Empty in domain mode, where the certificate is real; in IP mode it
    # skips CA checks but pins the self-signed key, which is stricter.
    local -a tls=()
    printf '\nAirspine hotspot setup\n\n'
    if [ ! -r /dev/tty ]; then
        echo "  Run this in a terminal window."
        exit 1
    fi
    for _ in 1 2 3; do
        read -rs -p "  Password: " pw </dev/tty; echo
        # printf is a builtin and curl reads stdin, so the password is never
        # on a command line where ps could show it.
        resp=$(printf '%s' "$pw" | curl -sS "${tls[@]}" \
               --data-binary @- -w '\n%{http_code}' "$url" 2>/dev/null)
        code=${resp##*$'\n'}
        body=${resp%$'\n'*}
        case $code in
            200) [ -n "$body" ] && break ;;
            403) echo "  Wrong password." ;;
            429) echo "  Too many wrong passwords. Ask for a new one."; exit 1 ;;
            404) echo "  This link has expired. Ask for a new one."; exit 1 ;;
            *)   echo "  Can't reach the Airspine server right now. Try again shortly."; exit 1 ;;
        esac
        body=""
    done
    unset pw
    [ -n "$body" ] || exit 1
    bash -c "$body"
}

main "$@"
