#!/usr/bin/env bash
# aitun.cc official installer
# Usage:  curl -fsSL https://aitun.cc/install.sh | bash
#   or:   curl -fsSL https://aitun.cc/install.sh | bash -s -- --version 4.9.36
#
# Installs the aitun tunnel client binary to /usr/local/bin/aitun (or
# ~/.local/bin/aitun when sudo is not available). Verifies SHA256 against
# aitun.cc/downloads/checksums-sha256.txt.

set -euo pipefail

# ---- defaults -------------------------------------------------------------
BASE_URL="https://aitun.cc/downloads"
INSTALL_DIR="/usr/local/bin"
BIN_NAME="aitun"
REQUESTED_VERSION=""

# ---- parse args (only --version for now) ---------------------------------
while [[ $# -gt 0 ]]; do
    case "$1" in
        --version)
            REQUESTED_VERSION="$2"
            shift 2
            ;;
        --help|-h)
            cat <<EOF
aitun installer
  curl -fsSL https://aitun.cc/install.sh | bash
  curl -fsSL https://aitun.cc/install.sh | bash -s -- --version 4.9.36
EOF
            exit 0
            ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1
            ;;
    esac
done

# ---- helpers --------------------------------------------------------------
info()  { printf '\033[1;34m\u2728\033[0m %s\n' "$*"; }
warn()  { printf '\033[1;33m\u26a0\ufe0f\033[0m %s\n' "$*" >&2; }
error() { printf '\033[1;31m\u274c\033[0m %s\n' "$*" >&2; }
die()   { error "$*"; exit 1; }

# ---- detect OS / arch -----------------------------------------------------
OS="$(uname -s)"
ARCH="$(uname -m)"
case "$OS" in
    Linux*)  PLATFORM_OS="linux" ;;
    Darwin*) PLATFORM_OS="darwin" ;;
    MINGW*|MSYS*|CYGWIN*)
        die "Windows detected. Please download the .exe directly from:
  https://aitun.cc/downloads/aitun-client-windows-amd64.exe
Or run in PowerShell:
  curl.exe -fsSL https://aitun.cc/downloads/aitun-client-windows-amd64.exe -o \$env:LOCALAPPDATA\\aitun.exe"
        ;;
    *) die "Unsupported OS: $OS" ;;
esac
case "$ARCH" in
    x86_64|amd64)   PLATFORM_ARCH="amd64" ;;
    aarch64|arm64)  PLATFORM_ARCH="arm64" ;;
    *) die "Unsupported architecture: $ARCH" ;;
esac

PLATFORM="${PLATFORM_OS}-${PLATFORM_ARCH}"
REMOTE_FILE="aitun-client-${PLATFORM}"
info "Detected platform: $PLATFORM"

# ---- pick install dir (sudo or not) --------------------------------------
SUDO=""
if [[ -w "$INSTALL_DIR" ]]; then
    TARGET="${INSTALL_DIR}/${BIN_NAME}"
elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then
    TARGET="${INSTALL_DIR}/${BIN_NAME}"
    SUDO="sudo"
else
    TARGET="${HOME}/.local/bin/${BIN_NAME}"
    mkdir -p "$(dirname "$TARGET")"
    warn "No sudo access — installing to $TARGET"
    warn "Make sure ${HOME}/.local/bin is in your PATH."
fi

# ---- pick version ---------------------------------------------------------
if [[ -z "$REQUESTED_VERSION" ]]; then
    info "Fetching latest version from $BASE_URL/latest-version.txt ..."
    REQUESTED_VERSION="$(curl -fsSL "$BASE_URL/latest-version.txt" | tr -d '[:space:]')"
    [[ -z "$REQUESTED_VERSION" ]] && die "Could not determine latest version."
fi
info "Installing aitun v$REQUESTED_VERSION"

# ---- download to temp file ------------------------------------------------
TMP_FILE="$(mktemp -t aitun-XXXXXX)"
trap 'rm -f "$TMP_FILE"' EXIT

URL="$BASE_URL/$REMOTE_FILE"
info "Downloading $URL ..."
if ! curl -fSL --retry 3 --retry-delay 2 -o "$TMP_FILE" "$URL"; then
    die "Download failed. Check your network or platform support."
fi

# ---- verify SHA256 --------------------------------------------------------
info "Verifying SHA256 checksum ..."
EXPECTED_HASH="$(curl -fsSL "$BASE_URL/checksums-sha256.txt" | awk -v f="$REMOTE_FILE" '$2==f {print $1; exit}')"
if [[ -z "$EXPECTED_HASH" ]]; then
    warn "No checksum entry found for $REMOTE_FILE — skipping verification."
else
    ACTUAL_HASH="$(sha256sum "$TMP_FILE" | awk '{print $1}')"
    if [[ "$EXPECTED_HASH" != "$ACTUAL_HASH" ]]; then
        die "Checksum mismatch!
  expected: $EXPECTED_HASH
  actual:   $ACTUAL_HASH"
    fi
    info "Checksum OK"
fi

# ---- install --------------------------------------------------------------
info "Installing to $TARGET ..."
if [[ -n "$SUDO" ]]; then
    $SUDO install -m 0755 "$TMP_FILE" "$TARGET"
else
    install -m 0755 "$TMP_FILE" "$TARGET"
fi

# ---- macOS quarantine notice ---------------------------------------------
if [[ "$PLATFORM_OS" == "darwin" ]]; then
    if command -v xattr >/dev/null 2>&1; then
        xattr -d com.apple.quarantine "$TARGET" 2>/dev/null || true
    fi
    warn "On macOS you may need to allow the binary in System Settings → Privacy & Security."
fi

# ---- verify ---------------------------------------------------------------
info "Verifying installation ..."
# aitun 用 --help 显示版本（不支持 --version），用 head -1 取首行
VERSION_OUT="$("$TARGET" --help 2>&1 | head -1 || true)"
if [[ -n "$VERSION_OUT" ]]; then
    info "Installed: $VERSION_OUT"
else
    warn "Binary installed but did not print version. Try: $TARGET --help"
fi

# ---- PATH hint ------------------------------------------------------------
case ":$PATH:" in
    *":$(dirname "$TARGET"):"*) ;;
    *)
        warn "$(dirname "$TARGET") is not in your PATH."
        warn "Add this line to your shell rc file:"
        warn "  export PATH=\"$(dirname "$TARGET"):\$PATH\""
        ;;
esac

echo
info "Done! Try it now:"
echo "    aitun --help"
echo "    aitun -p 8080                      # start a free HTTP tunnel"
echo "    aitun -k TOKEN --tcp-ports 22      # forward SSH"
echo "    aitun ssh-proxy host.t.aitun.cc 22 # use as SSH ProxyCommand"
echo
info "Docs: https://aitun.cc   |   Releases: https://aitun.cc/downloads/"
