#!/usr/bin/env bash
# NebulaSSH Linux Agent Installer
# Installs the agent binary and optionally sets up a systemd service.

set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

INSTALL_DIR="/usr/local/bin"
SERVICE_NAME="nebulassh-agent"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo -e "${CYAN}╔══════════════════════════════════════╗${NC}"
echo -e "${CYAN}║  NebulaSSH Linux Agent Installer     ║${NC}"
echo -e "${CYAN}╚══════════════════════════════════════╝${NC}"
echo ""

# Check root
if [[ $EUID -ne 0 ]]; then
    echo -e "${YELLOW}Note: Run with sudo for system-wide install + systemd service.${NC}"
    echo -e "Installing to user directory instead..."
    INSTALL_DIR="$HOME/.local/bin"
    mkdir -p "$INSTALL_DIR"
fi

# Check dependencies
echo -e "${CYAN}Checking dependencies...${NC}"
for cmd in curl python3 bash; do
    if command -v "$cmd" &>/dev/null; then
        echo -e "  ${GREEN}✓${NC} $cmd"
    else
        echo -e "  ${RED}✗${NC} $cmd (required)"
        if [[ "$cmd" == "curl" ]]; then
            echo -e "    Install: sudo apt install curl"
        elif [[ "$cmd" == "python3" ]]; then
            echo -e "    Install: sudo apt install python3"
        fi
    fi
done
echo ""

# Copy agent script
echo -e "${CYAN}Installing agent...${NC}"
cp "${SCRIPT_DIR}/nebulassh-agent" "${INSTALL_DIR}/nebulassh-agent"
chmod +x "${INSTALL_DIR}/nebulassh-agent"
echo -e "  ${GREEN}✓${NC} Installed to ${INSTALL_DIR}/nebulassh-agent"

# One-time enrollment token (required for a brand-new machine). Provide it via
# env: sudo NEBULASSH_ENROLL_TOKEN=NS-... ./install.sh
ENROLL_TOKEN="${NEBULASSH_ENROLL_TOKEN:-}"
if [[ -z "$ENROLL_TOKEN" ]]; then
    read -rp "Enter enrollment token (from Dashboard -> Agents & Connector): " ENROLL_TOKEN
fi

# Ask for relay URL
RELAY_URL=""
read -rp "Enter relay server URL [https://app.nebulassh.com]: " RELAY_URL
RELAY_URL="${RELAY_URL:-https://app.nebulassh.com}"

if [[ -z "$RELAY_URL" ]]; then
    echo -e "${YELLOW}No relay URL provided. You can set it later with:${NC}"
    echo -e "  nebulassh-agent --relay YOUR_URL"
else
    # Save initial config
    CONFIG_DIR="$HOME/.config/nebulassh"
    mkdir -p "$CONFIG_DIR"

    # Generate agent ID
    AGENT_ID=$("${INSTALL_DIR}/nebulassh-agent" --id 2>/dev/null || echo "unknown")

    cat > "${CONFIG_DIR}/agent.conf" <<EOF
relay_url=$RELAY_URL
agent_id=$AGENT_ID
shell=bash
poll_interval=2
EOF
    echo -e "  ${GREEN}✓${NC} Config saved to ${CONFIG_DIR}/agent.conf"
    echo -e "  ${GREEN}✓${NC} Agent ID: ${AGENT_ID}"
fi

# Setup systemd service (only if root)
if [[ $EUID -eq 0 ]] && [[ -n "$RELAY_URL" ]]; then
    echo ""
    read -rp "Setup systemd service for auto-start? (y/N): " setup_service

    if [[ "$setup_service" =~ ^[Yy] ]]; then
        RUN_USER="${SUDO_USER:-$(whoami)}"
        RUN_HOME=$(eval echo "~$RUN_USER")

        cat > "/etc/systemd/system/${SERVICE_NAME}.service" <<EOF
[Unit]
Description=NebulaSSH Linux Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$RUN_USER
Environment=HOME=$RUN_HOME
ExecStart=${INSTALL_DIR}/nebulassh-agent --relay $RELAY_URL --enroll-token $ENROLL_TOKEN
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

        systemctl daemon-reload
        systemctl enable "${SERVICE_NAME}.service"
        systemctl start "${SERVICE_NAME}.service"

        echo -e "  ${GREEN}✓${NC} Systemd service created and started"
        echo -e "  ${GREEN}✓${NC} Service will auto-start on boot"
        echo ""
        echo -e "Service commands:"
        echo -e "  sudo systemctl status ${SERVICE_NAME}"
        echo -e "  sudo systemctl stop ${SERVICE_NAME}"
        echo -e "  sudo systemctl restart ${SERVICE_NAME}"
        echo -e "  sudo journalctl -u ${SERVICE_NAME} -f"
    fi
fi

echo ""
echo -e "${GREEN}Installation complete!${NC}"
echo ""
echo -e "Usage:"
echo -e "  ${CYAN}nebulassh-agent --relay $RELAY_URL${NC}          # Run in foreground"
echo -e "  ${CYAN}nebulassh-agent --relay $RELAY_URL --daemon${NC}  # Run in background"
echo -e "  ${CYAN}nebulassh-agent --status${NC}                     # Check status"
echo -e "  ${CYAN}nebulassh-agent --stop${NC}                       # Stop agent"
