#!/usr/bin/env bash
# node-ubuntu_install.sh — One-liner installer/updater for AI-Network Proxy Node on Ubuntu/Debian
set -euo pipefail

echo "========================================="
echo " Installing AI-Network Proxy Node"
echo "========================================="

BASE_URL="http://124.70.180.22:8080/proxy-node-ubuntu"
INSTALL_DIR="$HOME/AI-Network-Node"
SERVICE_NAME="ai-network-node"

# ── 1. Discover latest release ──────────────────────────────────────
echo ""
echo "1. Discovering latest release..."

dir_html="$(curl -sS --connect-timeout 10 --max-time 15 "$BASE_URL/")" || {
    echo "   [error] Failed to reach the release server at $BASE_URL"
    exit 1
}

# Parse versions from links like node-ubuntu.v0.2.8.tar.gz
versions="$(echo "$dir_html" | grep -oP 'node-ubuntu\.\Kv[0-9]+\.[0-9]+\.[0-9]+(?=\.tar\.gz)' | sort -t. -k1,1V -k2,2V -k3,3V | uniq)"

if [[ -z "$versions" ]]; then
    echo "   [error] No release packages starting with node-ubuntu.v were discovered on the server."
    exit 1
fi

version="$(echo "$versions" | tail -1)"
echo "   [ok] Dynamically resolved latest version: $version"

# ── Auto-updater check ──────────────────────────────────────────────
LOCAL_VERSION_FILE="$INSTALL_DIR/bin/version.txt"
if [[ -f "$LOCAL_VERSION_FILE" ]]; then
    current_version="$(cat "$LOCAL_VERSION_FILE" | tr -d '[:space:]')"

    # Compare versions (strip leading 'v' for sort -V comparison)
    current_stripped="${current_version#v}"
    server_stripped="${version#v}"

    highest="$(printf '%s\n%s\n' "$current_stripped" "$server_stripped" | sort -V | tail -1)"

    if [[ "$highest" == "$current_stripped" && "$current_stripped" != "$server_stripped" ]] || [[ "$current_stripped" == "$server_stripped" ]]; then
        echo "   [info] You are already running the latest version ($current_version)!"
        echo ""
        echo "========================================="
        echo " No update required. Aborting installation."
        echo "========================================="
        exit 0
    fi
    echo "   [info] Proceeding with UPDATE: $current_version -> $version"
fi

# ── 2. Download package ─────────────────────────────────────────────
TAR_URL="$BASE_URL/node-ubuntu.$version.tar.gz"
TAR_PATH="/tmp/ai_network_${version}.tar.gz"

echo "2. Downloading package..."
curl -sS --connect-timeout 10 --max-time 120 -o "$TAR_PATH" "$TAR_URL" || {
    echo "   [error] Failed to download proxy package from $TAR_URL."
    exit 1
}
echo "   [ok] Download complete."

# ── 3. Prepare target directory ─────────────────────────────────────
echo "3. Preparing target directory..."

# Stop existing systemd service first
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
    echo "   [info] Stopping running service..."
    sudo systemctl stop "$SERVICE_NAME" 2>/dev/null || true
fi

if [[ -d "$INSTALL_DIR" ]]; then
    echo "   [info] Existing folder found. Halting background processes..."
    pkill -f "proxy-agent" 2>/dev/null || true
    pkill -f "frpc" 2>/dev/null || true
    pkill -f "gost" 2>/dev/null || true
    pkill -f "monitor-node.sh" 2>/dev/null || true

    sleep 2

    echo "   [info] Deleting existing directory..."
    rm -rf "$INSTALL_DIR" || {
        echo "   [error] Failed to delete existing folder: $INSTALL_DIR"
        echo "   Please ensure no other processes are using files in that folder, and try again."
        exit 1
    }
    echo "   [ok] Purged old installation."
fi
mkdir -p "$INSTALL_DIR"

# ── 4. Extract files ────────────────────────────────────────────────
echo "4. Extracting files to user folder..."
tar -xzf "$TAR_PATH" -C "$INSTALL_DIR"
echo "   [ok] Extracted."

# Ensure all scripts are executable
chmod +x "$INSTALL_DIR"/*.sh 2>/dev/null || true
chmod +x "$INSTALL_DIR"/bin/*.sh 2>/dev/null || true
chmod +x "$INSTALL_DIR"/bin/proxy-agent 2>/dev/null || true
chmod +x "$INSTALL_DIR"/bin/frpc 2>/dev/null || true
chmod +x "$INSTALL_DIR"/bin/gost 2>/dev/null || true

# ── 5. Clean up ─────────────────────────────────────────────────────
echo "5. Cleaning up temporary files..."
rm -f "$TAR_PATH"

# ── 6. Install systemd service ──────────────────────────────────────
echo "6. Installing systemd service..."

SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
CURRENT_USER="$(whoami)"

sudo bash -c "cat > '$SERVICE_FILE'" <<SERVICEEOF
[Unit]
Description=AI-Network Proxy Node
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
User=${CURRENT_USER}
WorkingDirectory=${INSTALL_DIR}/bin
ExecStart=/bin/bash ${INSTALL_DIR}/bin/start-node.sh
ExecStop=/bin/bash ${INSTALL_DIR}/bin/stop-node.sh
TimeoutStartSec=120
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target
SERVICEEOF

sudo systemctl daemon-reload
sudo systemctl enable "$SERVICE_NAME" --quiet
echo "   [ok] Service installed and enabled for auto-start on boot."

# ── 7. Start node ──────────────────────────────────────────────────
echo "7. Starting node..."
sudo systemctl start "$SERVICE_NAME"
echo "   [ok] Node is running!"

# ── 8. Shell aliases ───────────────────────────────────────────────
echo "8. Configuring shell aliases..."

SHELL_RC="$HOME/.bashrc"
[[ -f "$HOME/.zshrc" ]] && SHELL_RC="$HOME/.zshrc"

# Always replace the aliases block (handles upgrades from old format)
if grep -q "# AI-Network Node aliases" "$SHELL_RC" 2>/dev/null; then
    sed -i '/# AI-Network Node aliases/,/^$/d' "$SHELL_RC"
fi

cat >> "$SHELL_RC" <<'ALIASEOF'

# AI-Network Node aliases
alias ai-node-start='cd ~/AI-Network-Node && ./start-node.sh'
alias ai-node-stop='cd ~/AI-Network-Node && ./stop-node.sh'
alias ai-node-monitor='cd ~/AI-Network-Node && ./monitor-node.sh'

ALIASEOF
echo "   [ok] Shell aliases configured."

echo ""
echo "========================================="
echo -e " \033[32mInstallation Complete!\033[0m"
echo ""
echo " Your AI-Network node is installed and running at:"
echo -e " \033[33m$INSTALL_DIR\033[0m"
echo ""
echo -e " \033[36m★ The node will auto-start on system boot.\033[0m"
echo ""
echo " Commands:"
echo "    cd ~/AI-Network-Node && ./start-node.sh    # Start"
echo "    cd ~/AI-Network-Node && ./monitor-node.sh  # Monitor"
echo "    cd ~/AI-Network-Node && ./stop-node.sh     # Stop"
echo ""
echo " Or use aliases (reopen terminal):"
echo "    ai-node-start | ai-node-stop | ai-node-monitor"
echo "========================================="
