#!/bin/sh

# aishell-gate-network-install.sh — hosted at https://www.aishellgate.com/aishell-gate-network-install.sh
#   curl -fsSL https://www.aishellgate.com/aishell-gate-network-install.sh | sh
#   curl -fsSL https://www.aishellgate.com/aishell-gate-network-install.sh | sh -s -- --system
#   curl -fsSL https://www.aishellgate.com/aishell-gate-network-install.sh | sh -s -- --local
#
# Downloads the release tarball, verifies its checksum, and unpacks it to
# ~/aishell-gate/ -- always, regardless of what happens next. That part
# never needs root: it stages under $HOME no matter which way this goes.
#
# It then offers a choice for the BINARIES:
#
#   --system   install into /usr/local/bin, shared by every user on this
#              machine, plus man pages. Needs sudo.
#   --local    stay entirely under $HOME, no root ever. The server runs
#              in place from ~/aishell-gate/. This is the current
#              default behavior of this script, unchanged.
#   (neither)  ask, if there's a terminal to ask on; otherwise --local,
#              since that's the choice that never surprises anyone with
#              an unexpected password prompt.
#
# Whichever binary path is chosen, the MCP project wiring afterward always
# runs as the invoking user -- never root, never guessed from $SUDO_USER.
# See aishell-gate-mcp-install.sh for why that step refuses sudo outright,
# and aishell-gate-install.sh for why THIS script never re-execs itself as
# root either: doing so would resolve $HOME to root's home mid-staging.
# Because this script only ever shells out to `sudo` for the one command
# that needs it -- rather than becoming root itself -- $HOME and id -un()
# stay correct for the invoking user throughout, and the final MCP step
# needs no special-casing for which branch ran above it.
#
# Any arguments not consumed by --system/--local pass through unchanged to
# aishell-gate-mcp-install.sh (e.g. --project DIR, --client claude-code).

set -eu
BASE_URL="https://www.aishellgate.com"
ARCHIVE="$HOME/aishell-gate.tar.gz"

# Echo each command exactly as it runs, so you can see what's happening.
run() { printf '+ %s\n' "$*"; "$@"; }

echo "aishell-gate-network-install - installing from aishellgate.com."

# This check is about the STAGING step specifically, not about whether the
# binaries end up needing root -- that's asked further down, once $HOME is
# already known to be correct. Running this script ITSELF as root breaks
# the staging step: under sudo, $HOME typically resolves to /root, so the
# download would land somewhere the real user can't reach, silently.
if [ "$(id -u)" -eq 0 ]; then
    echo "ERROR: do not run this script itself as root or with sudo." >&2
    echo "It stages into \$HOME, which needs to be YOUR home directory," >&2
    echo "not root's. Run it as yourself -- it will ask about sudo on"    >&2
    echo "its own if a system-wide install makes sense."                 >&2
    exit 1
fi

# --system / --local decide how the BINARIES get installed. Anything else
# (e.g. --project DIR) is left in "$@" untouched, for the MCP install step
# at the very end.
SYSTEM_MODE=ask
while [ $# -gt 0 ]; do
    case "$1" in
        --system) SYSTEM_MODE=force; shift ;;
        --local)  SYSTEM_MODE=skip;  shift ;;
        *) break ;;
    esac
done

run curl -fsSL -o "$ARCHIVE" "$BASE_URL/download.php"
run curl -fsSL -o "$ARCHIVE.sha256" "$BASE_URL/checksum.php"

echo "verifying checksum..."
WANT=$(awk '{print $1}' "$ARCHIVE.sha256")
if command -v sha256sum >/dev/null 2>&1; then
    HAVE=$(sha256sum "$ARCHIVE" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
    HAVE=$(shasum -a 256 "$ARCHIVE" | awk '{print $1}')   # stock macOS has no sha256sum
else
    echo "ERROR: neither sha256sum nor shasum is available -- cannot verify." >&2
    exit 1
fi
[ "$HAVE" = "$WANT" ] || { echo "ERROR: checksum mismatch -- refusing to install" >&2; exit 1; }
echo "checksum OK"

run tar -xzf "$ARCHIVE" -C "$HOME"
rm -f "$ARCHIVE" "$ARCHIVE.sha256"
echo "unpacked to $HOME/aishell-gate"

# Is there a terminal to ask on? Prompting reads /dev/tty directly, not
# stdin, so this still works when the script arrives through `curl | sh`
# and stdin is occupied by the pipe carrying the script itself.
HAVE_TTY=0
if [ -e /dev/tty ] && ( : < /dev/tty ) 2>/dev/null; then HAVE_TTY=1; fi

DO_SYSTEM=0
case "$SYSTEM_MODE" in
    force) DO_SYSTEM=1 ;;
    skip)  DO_SYSTEM=0 ;;
    ask)
        if [ "$HAVE_TTY" -eq 1 ]; then
            echo ""
            printf 'Install system-wide, shared by every user on this machine?\n'
            printf 'Needs sudo. (/usr/local/bin plus man pages.)  [y/N]: '
            read -r ans < /dev/tty || ans=""
            case "$ans" in
                y|Y|yes|Yes) DO_SYSTEM=1 ;;
                *) DO_SYSTEM=0 ;;
            esac
        fi
        # No TTY and no explicit --system/--local: fall through with
        # DO_SYSTEM=0. A script piped in non-interactively should never
        # block on a prompt no one can answer, or start asking for a sudo
        # password nobody was told to expect.
        ;;
esac

if [ "$DO_SYSTEM" -eq 1 ]; then
    if ! command -v sudo >/dev/null 2>&1; then
        if [ "$SYSTEM_MODE" = force ]; then
            echo "ERROR: --system needs sudo, and no sudo binary was found." >&2
            exit 1
        fi
        echo "no sudo available -- continuing with the local install instead."
        DO_SYSTEM=0
    elif [ "$HAVE_TTY" -eq 1 ]; then
        if ! sudo -v; then
            if [ "$SYSTEM_MODE" = force ]; then
                echo "ERROR: --system needs sudo, and sudo access was not granted." >&2
                exit 1
            fi
            echo "sudo access not available -- continuing with the local install instead."
            DO_SYSTEM=0
        fi
    else
        # No terminal for sudo to prompt on either -- only proceed if
        # passwordless sudo is already configured (sudo -n fails instantly
        # rather than hanging when it isn't, which is what we want here).
        if ! sudo -n -v 2>/dev/null; then
            if [ "$SYSTEM_MODE" = force ]; then
                echo "ERROR: --system with no terminal available needs passwordless sudo, and none was found." >&2
                exit 1
            fi
            echo "no non-interactive sudo available -- continuing with the local install instead."
            DO_SYSTEM=0
        fi
    fi
fi

if [ "$DO_SYSTEM" -eq 1 ]; then
    echo "installing system-wide (you may be asked for your sudo password)..."
    # sudo -v above already authenticated (or confirmed passwordless sudo),
    # so this typically won't prompt again. aishell-gate-install.sh is
    # otherwise unchanged and unaware this script exists -- it only checks
    # that IT is running as root, which sudo here satisfies directly.
    run sudo sh "$HOME/aishell-gate/aishell-gate-install.sh"
else
    echo "installing for $(id -un) only, under \$HOME -- no root, no system-wide binaries."
    echo "(to upgrade later: sudo $HOME/aishell-gate/aishell-gate-install.sh)"
fi

echo ""
echo "wiring up MCP project..."
# Always as the invoking user -- never sudo, regardless of which branch
# ran above. aishell-gate-mcp-install.sh finds the server wherever it
# ended up: /usr/local/bin if --system ran, ~/.local/bin otherwise.
run sh "$HOME/aishell-gate/bin/MCP/aishell-gate-mcp-install.sh" "$@"

# One last, unambiguous line, printed after everything else -- including
# the MCP step's own "done" messages -- so there's a single place to look
# later and not have to scroll back through curl/tar/sudo output to
# remember which way this went.
echo ""
echo "-----------------------------------------------------"
if [ "$DO_SYSTEM" -eq 1 ]; then
    echo "Install summary: SYSTEM-WIDE"
    echo "  binaries : /usr/local/bin (shared by every user on this machine)"
    echo "  see the NOTE printed above for what system-wide does not do yet"
else
    echo "Install summary: LOCAL ONLY"
    echo "  binaries : $HOME/aishell-gate (this user only, no root used)"
    echo "  upgrade  : sudo $HOME/aishell-gate/aishell-gate-install.sh"
fi
echo "-----------------------------------------------------"
