#!/bin/sh
set +x
set -eu

VERSION='0.2.31-1'
BASE_URL='https://downloads.homereach.jitoma.cz'
ADMIN_PORT='58443'
SYSTEM_HOST='/opt/homereach-host/bin/homereach-host'
USER_HOST_DIRECTORY='.local/lib/homereach-host'
SERVICE='homereach-host.service'
MODE=''
HOST=''
SYSTEMCTL_SCOPE=''
DOWNLOAD_TIMEOUT='180'
CONNECT_TIMEOUT='15'
DOWNLOAD_MAXIMUM_BYTES='67108864'
CHECKSUM_MAXIMUM_BYTES='512'
SHA256_HEX_CHARACTERS='64'
PASSWORD_MINIMUM='12'
PASSWORD_MAXIMUM='256'
SYSTEMD_MINIMUM='247'
TEMP_DIRECTORY=''
TEMP_BASE=${TMPDIR:-/var/tmp}
TTY_STATE=''
ACCENT=''
SUCCESS=''
MUTED=''
RESET=''
DNS_SERVER=''
HOME_INTERFACE=''
USERSPACE_FORWARDING=''
KERNEL_FORWARDING=''
ALLOW_FIREWALL_FORWARDING=''

cleanup() {
    if [ -n "$TTY_STATE" ]; then stty "$TTY_STATE" </dev/tty || true; fi
    if [ -n "$TEMP_DIRECTORY" ]; then
        case "$TEMP_DIRECTORY" in "$TEMP_BASE"/homereach-install.*) rm -rf -- "$TEMP_DIRECTORY" ;; esac
    fi
}

say() { printf '%s\n' "$*"; }
step() { printf '\n%s%s%s\n' "$ACCENT" "$*" "$RESET"; }
fail() { printf '\nHomeReach could not continue: %s\n' "$*" >&2; exit 1; }
ask() { printf '\n%s ' "$1" >/dev/tty; IFS= read -r ANSWER </dev/tty || fail 'No answer received.'; }
confirmed() { case "$ANSWER" in y|Y|yes|YES) return 0 ;; *) return 1 ;; esac; }
service_control() { if [ "$MODE" = user ]; then systemctl --user "$@"; else systemctl "$@"; fi; }

download() {
    curl --proto '=https' --tlsv1.2 --fail --silent --show-error --location \
        --connect-timeout "$CONNECT_TIMEOUT" --max-time "$DOWNLOAD_TIMEOUT" --max-filesize "$3" "$1" -o "$2"
}

password() {
    trap '' TSTP
    TTY_STATE=$(stty -g </dev/tty)
    stty -echo </dev/tty
    printf '\nChoose an admin password (12–256 bytes): ' >/dev/tty
    IFS= read -r ADMIN_PASSWORD </dev/tty || fail 'No password received.'
    printf '\nConfirm admin password: ' >/dev/tty
    IFS= read -r CONFIRM_PASSWORD </dev/tty || fail 'No confirmation received.'
    stty "$TTY_STATE" </dev/tty
    TTY_STATE=''
    trap - TSTP
    printf '\n' >/dev/tty
    [ "$ADMIN_PASSWORD" = "$CONFIRM_PASSWORD" ] || fail 'Passwords do not match. Nothing has been installed.'
    PASSWORD_BYTES=$(LC_ALL=C printf %s "$ADMIN_PASSWORD" | wc -c | tr -d ' ')
    [ "$PASSWORD_BYTES" -ge "$PASSWORD_MINIMUM" ] && [ "$PASSWORD_BYTES" -le "$PASSWORD_MAXIMUM" ] \
        || fail 'Use a password between 12 and 256 bytes. Nothing has been installed.'
    unset CONFIRM_PASSWORD
}

main() {
    while [ "$#" -gt 0 ]; do
        case "$1" in
            --dns-server) [ "$#" -ge 2 ] || fail '--dns-server needs an IP address.'; DNS_SERVER=$2; shift 2 ;;
            --home-interface) [ "$#" -ge 2 ] || fail '--home-interface needs a network interface name.'; HOME_INTERFACE=$2; shift 2 ;;
            --userspace-forwarding) USERSPACE_FORWARDING=1; shift ;;
            --kernel-forwarding) KERNEL_FORWARDING=1; shift ;;
            --allow-firewall-forwarding) ALLOW_FIREWALL_FORWARDING=1; shift ;;
            --userspace) fail '--userspace is now called --userspace-forwarding.' ;;
            --help) say 'HomeReach installer: sh install.sh [--dns-server IP] [--home-interface NAME] [--userspace-forwarding | --kernel-forwarding] [--allow-firewall-forwarding]'; return ;;
            *) fail "Unknown option: $1" ;;
        esac
    done
    [ -z "$USERSPACE_FORWARDING" ] || [ -z "$KERNEL_FORWARDING$ALLOW_FIREWALL_FORWARDING" ] \
        || fail '--userspace-forwarding cannot be combined with --kernel-forwarding or --allow-firewall-forwarding.'
    [ "$(uname -s)" = Linux ] || fail 'This installer is for Linux.'
    [ -r /dev/tty ] && [ -w /dev/tty ] || fail 'An interactive terminal is required. Run this command in an SSH or local terminal.'
    for TOOL in curl sha256sum tar mktemp stty systemctl id wc tr grep head awk tail cat; do
        command -v "$TOOL" >/dev/null 2>&1 || fail "Install $TOOL first; the script will not change your package manager."
    done
    [ -d /run/systemd/system ] || fail 'systemd must already be running. No files have been installed.'
    SYSTEMD_VERSION=$(systemctl --version | head -n 1 | awk '{print $2}')
    [ "$SYSTEMD_VERSION" -ge "$SYSTEMD_MINIMUM" ] || fail 'HomeReach needs systemd 247 or newer.'
    if [ "$(id -u)" = 0 ]; then
        MODE=system; HOST=$SYSTEM_HOST; SYSTEMCTL_SCOPE=''
    else
        MODE=user; SYSTEMCTL_SCOPE='--user '
        case "${HOME:-}" in /*) ;; *) fail 'HOME must name your absolute home directory for a per-user installation.' ;; esac
        HOST="$HOME/$USER_HOST_DIRECTORY/homereach-host"
        [ -n "${XDG_RUNTIME_DIR:-}" ] && systemctl --user show-environment >/dev/null 2>&1 \
            || fail 'A per-user installation needs your systemd user session. Sign in through SSH or a desktop session and run this again, or run the installer as root (sudo) for a system installation. Nothing has been installed.'
    fi
    if [ -t 1 ] && [ "${TERM:-dumb}" != dumb ] && [ -z "${NO_COLOR+x}" ]; then
        if [ "${COLORTERM:-}" = truecolor ] || [ "${COLORTERM:-}" = 24bit ]; then
            ACCENT=$(printf '\033[38;2;230;92;60m'); SUCCESS=$(printf '\033[38;2;101;109;78m')
            MUTED=$(printf '\033[38;2;116;117;108m')
        else
            ACCENT=$(printf '\033[38;5;166m'); SUCCESS=$(printf '\033[38;5;65m')
            MUTED=$(printf '\033[38;5;243m')
        fi
        RESET=$(printf '\033[0m')
    fi
    case "$(uname -m)" in x86_64|amd64) ARCH='x64' ;; aarch64|arm64) ARCH='arm64' ;; *) fail 'Only Linux x64 and ARM64 are supported.' ;; esac
    trap cleanup 0
    trap 'exit 130' INT
    trap 'exit 143' TERM HUP
    step '⌂  HomeReach · a simpler way home'
    say "Linux $ARCH · $VERSION"
    if [ "$MODE" = system ]; then
        say 'Running as root: this installs the system host with its own service account.'
    else
        say 'Running without root: this installs HomeReach for your account only. Nothing here asks for sudo.'
        say 'For a system-wide service instead, run the installer as root, for example: curl -fsSL https://homereach.jitoma.cz/install.sh | sudo sh'
    fi
    say 'We will download and verify Home Host before changing anything.'
    say 'No public IP, router port forwarding, reboot, or private key upload is needed.'
    step '1 / 4 · Download and verify · no sudo'
    TEMP_BASE=${TEMP_BASE%/}
    case "$TEMP_BASE" in /*) ;; *) fail 'TMPDIR must name an absolute temporary directory.' ;; esac
    [ -d "$TEMP_BASE" ] && [ -w "$TEMP_BASE" ] || fail 'The temporary directory is unavailable. Set TMPDIR to a writable directory.'
    TEMP_DIRECTORY=$(mktemp -d "$TEMP_BASE/homereach-install.XXXXXXXX")
    say "Temporary staging: $TEMP_DIRECTORY · removed when this installer exits."
    PACKAGE="homereach-host-$VERSION-linux-$ARCH.tar.gz"
    download "$BASE_URL/$VERSION/$PACKAGE" "$TEMP_DIRECTORY/$PACKAGE" "$DOWNLOAD_MAXIMUM_BYTES" || fail 'Download failed. No system changes were made.'
    download "$BASE_URL/$VERSION/$PACKAGE.sha256" "$TEMP_DIRECTORY/$PACKAGE.sha256" "$CHECKSUM_MAXIMUM_BYTES" || fail 'Checksum download failed. No system changes were made.'
    IFS=' ' read -r EXPECTED_DIGEST CHECKSUM_FILENAME <"$TEMP_DIRECTORY/$PACKAGE.sha256" || fail 'The checksum file is incomplete.'
    [ "$CHECKSUM_FILENAME" = "$PACKAGE" ] && [ "${#EXPECTED_DIGEST}" -eq "$SHA256_HEX_CHARACTERS" ] || fail 'The checksum file does not match this package.'
    case "$EXPECTED_DIGEST" in *[!0-9a-f]*) fail 'The checksum has an invalid format.' ;; esac
    ACTUAL_DIGEST=$(sha256sum "$TEMP_DIRECTORY/$PACKAGE")
    [ "${ACTUAL_DIGEST%% *}" = "$EXPECTED_DIGEST" ] || fail 'Checksum mismatch. The package will not be installed.'
    tar -xzf "$TEMP_DIRECTORY/$PACKAGE" -C "$TEMP_DIRECTORY"
    [ -x "$TEMP_DIRECTORY/homereach-host" ] || fail 'Verified package is missing its host executable.'
    "$TEMP_DIRECTORY/homereach-host" --version >/dev/null 2>&1 || fail 'This temporary directory cannot run HomeReach. Set TMPDIR to a writable directory that allows execution, then run the installer again. Nothing has been installed.'
    say "Verified SHA-256 · $PACKAGE"
    set -- check-install
    if [ -n "$USERSPACE_FORWARDING" ]; then set -- "$@" --userspace-forwarding; fi
    if [ -n "$KERNEL_FORWARDING" ]; then set -- "$@" --kernel-forwarding; fi
    if [ -n "$ALLOW_FIREWALL_FORWARDING" ]; then set -- "$@" --allow-firewall-forwarding; fi
    "$TEMP_DIRECTORY/homereach-host" "$@" || fail 'Nothing has been installed.'
    step '2 / 4 · Your browser administration · no sudo'
    say "Your host's administration page opens at http://127.0.0.1:$ADMIN_PORT on this computer, or over an SSH tunnel."
    say 'Home-network access is optional: turn it on later in that page. It uses HTTPS, your password and the private subnet you choose.'
    password
    if [ "$MODE" = system ]; then
        step '3 / 4 · System installation · as root'
        say 'WHAT: create the dedicated non-root homereach-host service user; install binaries in /opt/homereach-host;'
        say '      store protected settings in /etc/homereach-host and identity in /var/lib/homereach-host;'
        say '      create, enable, and start homereach-host.service immediately.'
        say 'WHY: a system service keeps running after you close SSH and starts at boot.'
        if [ -n "$USERSPACE_FORWARDING" ]; then
            say 'The running service forwards in userspace with no extra privileges or capabilities; it does not run as root.'
        else
            say 'A new system host forwards through the Linux kernel: it holds CAP_NET_ADMIN, /dev/net/tun and writable kernel'
            say '      tunables to switch on IP forwarding, and does not run as root. Reinstalling keeps the current forwarding mode;'
            say '      --userspace-forwarding keeps the service capability-free and --kernel-forwarding switches an existing'
            say '      userspace host to the kernel. If this computer cannot forward through the kernel, or a firewall would block'
            say '      forwarding, the installer asks before changing anything.'
        fi
        ask 'Install and start HomeReach as a system service? [y/N]'
    else
        step '3 / 4 · Install for your account · no sudo'
        say "WHAT: install the host in ~/$USER_HOST_DIRECTORY, settings in \$XDG_CONFIG_HOME/homereach-host (by default"
        say '      ~/.config/homereach-host) and identity in $XDG_STATE_HOME/homereach-host (by default ~/.local/state/homereach-host);'
        say '      create, enable, and start your own homereach-host.service (systemctl --user). It forwards in userspace.'
        say 'WHY: a per-user service needs no administrator. If your system allows it, lingering keeps it running after you'
        say '     sign out and starts it at boot; otherwise it runs while you are signed in.'
        ask 'Install and start HomeReach for your account? [y/N]'
    fi
    if ! confirmed; then
        unset ADMIN_PASSWORD
        say 'Installation cancelled. Temporary downloads will be removed; your system was not changed.'
        return
    fi
    set -- "$TEMP_DIRECTORY/homereach-host"
    if [ -n "$DNS_SERVER" ]; then set -- "$@" --dns-server "$DNS_SERVER"; fi
    if [ -n "$HOME_INTERFACE" ]; then set -- "$@" --home-interface "$HOME_INTERFACE"; fi
    set -- "$@" install
    if [ -n "$USERSPACE_FORWARDING" ]; then set -- "$@" --userspace-forwarding; fi
    if [ -n "$KERNEL_FORWARDING" ]; then set -- "$@" --kernel-forwarding; fi
    if [ -n "$ALLOW_FIREWALL_FORWARDING" ]; then set -- "$@" --allow-firewall-forwarding; fi
    say 'Installing private files and starting the host… Initial startup can take up to 90 seconds.'
    if ! "$@" >"$TEMP_DIRECTORY/install.log" 2>&1; then
        tail -n 30 "$TEMP_DIRECTORY/install.log" >&2
        fail 'Service installation failed. Review the error above; HomeReach was not marked ready.'
    fi
    if ! printf %s "$ADMIN_PASSWORD" | "$HOST" configure-admin --password-file - >"$TEMP_DIRECTORY/admin.log" 2>&1; then
        unset ADMIN_PASSWORD
        cat "$TEMP_DIRECTORY/admin.log" >&2
        fail "The host was installed, but administration setup failed. Administration settings may have changed; inspect systemctl ${SYSTEMCTL_SCOPE}status $SERVICE. Firewall permissions granted during installation stay recorded and are removed by uninstall."
    fi
    unset ADMIN_PASSWORD
    step '4 / 4 · Your host is running'
    service_control is-active --quiet "$SERVICE" || fail "The service is not running. Inspect systemctl ${SYSTEMCTL_SCOPE}status $SERVICE."
    printf '%s✓ Installed · enabled · running now%s\n' "$SUCCESS" "$RESET"
    if [ "$MODE" = system ]; then
        say 'You can close this SSH session. No reboot is required.'
    else
        grep -q 'keeps running after you sign out' "$TEMP_DIRECTORY/install.log" \
            && say 'You can close this SSH session. No reboot is required.' \
            || grep 'runs while you are signed in' "$TEMP_DIRECTORY/install.log" || true
    fi
    cat "$TEMP_DIRECTORY/admin.log"
    grep 'from your application menu' "$TEMP_DIRECTORY/install.log" || true
    say "From another computer, use: ssh -L $ADMIN_PORT:127.0.0.1:$ADMIN_PORT USER@HOST"
    say "Replace USER@HOST with your SSH login, then open http://localhost:$ADMIN_PORT."
    step 'Make it yours · scan this public identity'
    "$HOST" identity --qr
    say 'On your phone, open https://homereach.jitoma.cz/account/hosts → Register Home Host → Scan host QR.'
    say 'The QR contains only your public identity. Start account linking on the website, then confirm the request with this host’s private four-digit code.'
    if [ "$MODE" = system ]; then
        say "Show an active code: sudo $HOST pairing-code"
        say "Remove HomeReach: sudo $HOST uninstall (add --purge to also delete its identity and settings)"
    else
        say "Show an active code: $HOST pairing-code"
        say "Remove HomeReach: $HOST uninstall (add --purge to also delete its identity and settings)"
    fi
    say "Status: systemctl ${SYSTEMCTL_SCOPE}status $SERVICE"
    printf '\n%sWelcome home.%s\n' "$ACCENT" "$RESET"
}

main "$@"
