#!/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
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
    if [ "$(id -u)" -ne 0 ]; then
        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"
    SERVICE_FILE="/etc/systemd/system/servermanager-agent.service"
    USE_SYSTEMD=true
    INSTALL_MODE="system"
else
    AGENT_BIN="$HOME/.local/bin/servermanager-agent"
    USE_SYSTEMD=false
    INSTALL_MODE="user"
fi

echo "[1/3] Creating directory..."
mkdir -p "$(dirname "$AGENT_BIN")"

echo "[2/3] Installing agent binary..."
cat > "$AGENT_BIN" << EOF
#!/bin/bash

SERVER_URL="$SERVER_URL"
AGENT_KEY="$AGENT_KEY"
INTERVAL=$INTERVAL

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

push_metrics() {
    payload=\$(cat << PAYLOAD
{
    "agent_key": "\$AGENT_KEY",
    "cpu": \$CPU,
    "ram": \$RAM,
    "disk": \$DISK,
    "load": \$LOAD,
    "uptime": "\$UPTIME"
}
PAYLOAD
)
    local code
    code=\$(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) || code=0
    echo "\$code"
}

echo "ServerManager Agent started"
echo "  Server: $SERVER_URL/api/metrics/push"
echo "  Interval: \${INTERVAL}s"
echo "  Host: \$(hostname)"
sleep 2
while true; do
    collect_metrics
    http_code=\$(push_metrics)
    echo "[\$(date)] HTTP \$http_code"
    if [ "\$http_code" = "0" ]; then
        echo "  curl failed — check SERVER_URL=$SERVER_URL"
    fi
    sleep "\$INTERVAL"
done
EOF

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/3] 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)..."
    LOG_DIR="$HOME/.local/share/servermanager"
    mkdir -p "$LOG_DIR"
    CRON_JOB="@reboot $AGENT_BIN > $LOG_DIR/agent.log 2>&1"
    (crontab -l 2>/dev/null | grep -v 'servermanager-agent'; echo "$CRON_JOB") | crontab - 2>/dev/null || {
        echo "WARNING: Could not install crontab."
        echo "  Run: $AGENT_BIN &"
    }
    echo "  Starting agent in background..."
    nohup "$AGENT_BIN" > "$LOG_DIR/agent.log" 2>&1 & disown
    echo "  Agent started (PID $!)"
fi

echo ""
echo "ServerManager Agent installed successfully!"
echo "  Mode: $INSTALL_MODE"
echo "  Binary: $AGENT_BIN"
echo "  Config: embedded in binary (no external config file)"
