#!/usr/bin/env bash
# zagent official installer
# Usage:
#   curl -fsSL https://zagent.samai.cc/install.sh | bash
#   curl -fsSL https://zagent.samai.cc/install.sh | bash -s -- --version 0.28.23
#
# Installs ZAgent ¡ª the lightweight cross-platform AI agent for AICQ.
# Downloads the standalone binary tar.gz for Linux or macOS, extracts it,
# installs `zagent` to /usr/local/bin (or ~/.local/bin if no sudo), and
# prints next-step usage. No source code is shipped; no git clone is performed.

set -euo pipefail

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

# ---- parse args -----------------------------------------------------------
while [[ $# -gt 0 ]]; do
    case "$1" in
        --version) REQUESTED_VERSION="$2"; shift 2 ;;
        --help|-h)
            echo "zagent installer"
            echo "  curl -fsSL https://zagent.samai.cc/install.sh | bash"
            echo "  curl -fsSL https://zagent.samai.cc/install.sh | bash -s -- --version 0.28.23"
            exit 0 ;;
        *) echo "Unknown option: $1" >&2; exit 1 ;;
    esac
done

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

echo
echo "¨X¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨["
echo "¨U       ZAgent Installer                   ¨U"
echo "¨U       Lightweight AI Agent for AICQ      ¨U"
echo "¨^¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨a"
echo

# ---- 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. Run in PowerShell: irm https://zagent.samai.cc/install.ps1 | iex" ;;
    *) 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}"
info "Detected platform: $PLATFORM"

# Termux detection (install to $PREFIX/bin if writable)
TERMUX_MODE=false
if [[ -n "${TERMUX_VERSION:-}" ]] || [[ -d "/data/data/com.termux" && "${PLATFORM_OS}" == "linux" ]]; then
    if [[ -d "${PREFIX:-/data/data/com.termux/files/usr}" && -w "${PREFIX:-/data/data/com.termux/files/usr}/bin" ]]; then
        TERMUX_MODE=true
        INSTALL_DIR="${PREFIX}/bin"
        info "Termux detected, install dir: $INSTALL_DIR"
    fi
fi

# ---- 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"
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:]' || true)"
    [[ -z "$REQUESTED_VERSION" ]] && die "Could not determine latest version."
fi
info "Installing zagent v$REQUESTED_VERSION"

# ---- download + extract ---------------------------------------------------
ARCHIVE_NAME="zagent-${PLATFORM}.tar.gz"
ARCHIVE_URL="$BASE_URL/$ARCHIVE_NAME"
TMP_FILE="$(mktemp -t zagent-XXXXXX)"
TMP_DIR="$(mktemp -d -t zagent-extract-XXXXXX)"
trap 'rm -f "$TMP_FILE"; rm -rf "$TMP_DIR"' EXIT

info "Downloading $ARCHIVE_URL ..."
if ! curl -fSL --retry 3 --retry-delay 2 -o "$TMP_FILE" "$ARCHIVE_URL"; then
    die "Download failed."
fi

# ---- verify SHA256 --------------------------------------------------------
info "Verifying SHA256 checksum ..."
EXPECTED_HASH="$(curl -fsSL "$BASE_URL/checksums-sha256.txt" 2>/dev/null | awk -v f="$ARCHIVE_NAME" '$2==f {print $1; exit}' || true)"
if [[ -n "$EXPECTED_HASH" ]]; then
    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"
else
    warn "No checksum entry for $ARCHIVE_NAME - skipping verification."
fi

# ---- extract --------------------------------------------------------------
info "Extracting archive ..."
tar -xzf "$TMP_FILE" -C "$TMP_DIR"

# Locate the zagent binary inside the extracted archive.
# The archive layout is either:
#   ./zagent                   (flat)
#   ./zagent-<ver>/zagent      (versioned top dir)
BINARY_SRC=""
for candidate in \
    "$TMP_DIR/zagent" \
    "$TMP_DIR/./zagent" \
    "$TMP_DIR/zagent-$REQUESTED_VERSION/zagent" \
    "$(find "$TMP_DIR" -type f -name zagent -perm -u+x | head -1)"; do
    if [[ -f "$candidate" && -x "$candidate" ]]; then
        BINARY_SRC="$candidate"
        break
    fi
done
if [[ -z "$BINARY_SRC" ]]; then
    # fall back to first file named zagent even if not +x
    BINARY_SRC="$(find "$TMP_DIR" -type f -name zagent | head -1)"
    [[ -z "$BINARY_SRC" ]] && die "zagent binary not found inside archive."
fi

# Some archives ship a `web/` directory next to the binary; install it too
# so the built-in web UI assets are available.
WEB_SRC="$TMP_DIR/web"
if [[ ! -d "$WEB_SRC" ]]; then
    WEB_SRC="$(dirname "$BINARY_SRC")/web"
fi

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

# ---- install web assets (best-effort) ------------------------------------
INSTALL_WEB_DIR=""
if [[ -d "$WEB_SRC" ]]; then
    if [[ "$PLATFORM_OS" == "darwin" ]]; then
        INSTALL_WEB_DIR="${HOME}/.zagent/web"
    else
        INSTALL_WEB_DIR="${HOME}/.zagent/web"
    fi
    mkdir -p "$INSTALL_WEB_DIR"
    if [[ -n "$SUDO" ]]; then
        $SUDO cp -r "$WEB_SRC/." "$INSTALL_WEB_DIR/" 2>/dev/null || cp -r "$WEB_SRC/." "$INSTALL_WEB_DIR/" 2>/dev/null || true
    else
        cp -r "$WEB_SRC/." "$INSTALL_WEB_DIR/" 2>/dev/null || true
    fi
    info "Web assets installed to $INSTALL_WEB_DIR"
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

# ---- PATH hint ------------------------------------------------------------
case ":$PATH:" in
    *":$(dirname "$TARGET"):"*) ;;
    *)
        warn "$(dirname "$TARGET") is not in your PATH."
        if [[ "$TARGET" == "$HOME/.local/bin/zagent" ]]; then
            warn "Add this to your shell rc file: export PATH=\"\$HOME/.local/bin:\$PATH\""
        fi ;;
esac

echo
info "Done! Try it now:"
echo "    zagent -name ZAgent -code WVJFDK                      # start with Web UI (port 8181)"
echo "    zagent -name ZAgent -code WVJFDK -daemon -log-file z.log   # run as daemon"
echo "    zagent -nowebui -name ZAgent -log-file z.log         # headless server mode"
echo
info "Docs: https://zagent.samai.cc   |   Releases: https://zagent.samai.cc/downloads/"
info "Source: https://github.com/samaidev/zagent_r"
