#!/bin/bash
# ServerManager Agent Installer
# Usage: bash agent-install.sh <SERVER_URL> <AGENT_KEY> [INTERVAL]

SERVER_URL="${1:-}"
AGENT_KEY="${2:-}"
INTERVAL="${3:-60}"

if [ -z "$SERVER_URL" ] || [ -z "$AGENT_KEY" ]; then
    echo "Usage: bash agent-install.sh <SERVER_URL> <AGENT_KEY> [INTERVAL]"
    exit 1
fi

# Detect if we can run as root (try non-interactive sudo)
CAN_ROOT=false
if [ "$(id -u)" -eq 0 ]; then
    CAN_ROOT=true
elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then
    CAN_ROOT=true
fi

if [ "$CAN_ROOT" = true ]; then
    # ── Root/system mode ──
    if [ "$(id -u)" -ne 0 ]; then
        # Re-exec with script PTY if available (handles requiretty)
        if command -v script >/dev/null 2>&1; then
            exec script -q -c "sudo bash '$0' '$1' '$2' '$3'" /dev/null
        fi
        exec sudo bash "$0" "$@"
    fi

    AGENT_BIN="/usr/local/bin/servermanager-agent"
    CONFIG_DIR="/etc/servermanager"
    CONFIG_FILE="$CONFIG_DIR/agent.conf"
    SERVICE_FILE="/etc/systemd/system/servermanager-agent.service"
    USE_SYSTEMD=true
    INSTALL_MODE="system"
else
    # ── User/no-root mode ──
    AGENT_BIN="$HOME/.local/bin/servermanager-agent"
    CONFIG_DIR="$HOME/.config/servermanager"
    CONFIG_FILE="$CONFIG_DIR/agent.conf"
    USE_SYSTEMD=false
    INSTALL_MODE="user"
fi

echo "[1/4] Creating directories..."
mkdir -p "$(dirname "$AGENT_BIN")"
mkdir -p "$CONFIG_DIR"

echo "[2/4] Installing agent binary..."
cat > "$AGENT_BIN" << 'AGENTSCRIPT'
#!/bin/bash
set -e

CONFIG_FILE="${1:-$HOME/.config/servermanager/agent.conf}"

load_config() {
    if [ -f "$CONFIG_FILE" ]; then
        source "$CONFIG_FILE"
    fi
    SERVER_URL="${SERVER_URL:-}"
    AGENT_KEY="${AGENT_KEY:-}"
    INTERVAL="${INTERVAL:-60}"
}

collect_metrics() {
    CPU=$(top -bn1 2>/dev/null | grep 'Cpu(s)' | awk '{print $2}' | cut -d'%' -f1)
    [ -z "$CPU" ] && CPU=0
    RAM=$(free 2>/dev/null | grep Mem | awk '{printf "%.1f", $3/$2 * 100}')
    [ -z "$RAM" ] && RAM=0
    DISK=$(df / 2>/dev/null | tail -1 | awk '{print $5}' | sed 's/%//')
    [ -z "$DISK" ] && DISK=0
    LOAD=$(cat /proc/loadavg 2>/dev/null | awk '{print $1}')
    [ -z "$LOAD" ] && LOAD=0
    UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //')
    [ -z "$UPTIME" ] && UPTIME=""
}

push_metrics() {
    payload=$(cat <<EOF
{
    "agent_key": "$AGENT_KEY",
    "cpu": $CPU,
    "ram": $RAM,
    "disk": $DISK,
    "load": $LOAD,
    "uptime": "$UPTIME"
}
EOF
)
    curl -s -X POST "$SERVER_URL/api/metrics/push" \
        -H "Content-Type: application/json" \
        -d "$payload" \
        --connect-timeout 10 --max-time 30 \
        -o /dev/null -w "%{http_code}" 2>/dev/null || echo "000"
}

run() {
    load_config
    if [ -z "$SERVER_URL" ] || [ -z "$AGENT_KEY" ]; then
        echo "ERROR: SERVER_URL and AGENT_KEY not configured"
        exit 1
    fi
    echo "ServerManager Agent started (interval: ${INTERVAL}s)"
    sleep 2
    while true; do
        collect_metrics
        http_code=$(push_metrics)
        echo "[$(date)] HTTP $http_code"
        sleep "$INTERVAL"
    done
}

run
AGENTSCRIPT
chmod +x "$AGENT_BIN"

if [ ! -f "$AGENT_BIN" ]; then
    echo "ERROR: Agent binary was not created"
    exit 1
fi
echo "  Binary: $AGENT_BIN ($(wc -c < "$AGENT_BIN") bytes)"

echo "[3/4] Writing config..."
cat > "$CONFIG_FILE" << EOF
SERVER_URL="$SERVER_URL"
AGENT_KEY="$AGENT_KEY"
INTERVAL=$INTERVAL
EOF
chmod 600 "$CONFIG_FILE"

echo "[4/4] Enabling auto-start..."

if [ "$USE_SYSTEMD" = true ]; then
    echo "  Using systemd service..."
    cat > "$SERVICE_FILE" << 'UNIT'
[Unit]
Description=ServerManager Monitoring Agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/local/bin/servermanager-agent
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
UNIT
    systemctl daemon-reload 2>/dev/null || true
    systemctl enable servermanager-agent 2>/dev/null || true
    systemctl restart servermanager-agent 2>/dev/null || true
else
    echo "  Using crontab (@reboot)..."
    CRON_JOB="@reboot $AGENT_BIN > $CONFIG_DIR/agent.log 2>&1"
    (crontab -l 2>/dev/null | grep -v '_sm_agent\|servermanager-agent'; echo "$CRON_JOB") | crontab - 2>/dev/null || {
        echo "WARNING: Could not install crontab. Agent must be started manually."
        echo "  Run: $AGENT_BIN &"
    }
fi

echo ""
echo "ServerManager Agent installed successfully!"
echo "  Mode: $INSTALL_MODE"
echo "  Binary: $AGENT_BIN"
echo "  Config: $CONFIG_FILE"
