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

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

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"

echo "[1/5] Creating config directory..."
mkdir -p "$CONFIG_DIR"

echo "[2/5] Installing agent binary..."
mkdir -p "$(dirname "$AGENT_BIN")"
cat > "$AGENT_BIN" << 'AGENTSCRIPT'
#!/bin/bash
set -e
CONFIG_FILE="/etc/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"
}

main() {
    load_config
    if [ -z "$SERVER_URL" ] || [ -z "$AGENT_KEY" ]; then
        echo "ERROR: SERVER_URL and AGENT_KEY must be set in $CONFIG_FILE"
        exit 1
    fi
    echo "ServerManager Agent started (interval: ${INTERVAL}s)"
    sleep 2
    while true; do
        collect_metrics
        http_code=$(push_metrics)
        if [ "$http_code" = "200" ]; then
            echo "[$(date)] Metrics pushed successfully"
        else
            echo "[$(date)] Failed to push metrics (HTTP $http_code)"
        fi
        sleep "$INTERVAL"
    done
}
main
AGENTSCRIPT
chmod +x "$AGENT_BIN"

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

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

echo "[4/5] Installing systemd service..."
cat > "$SERVICE_FILE" << 'UNIT'
[Unit]
Description=ServerManager Monitoring Agent
Documentation=https://github.com/servermanager
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/servermanager-agent
Restart=always
RestartSec=10
StartLimitIntervalSec=60
StartLimitBurst=5
NoNewPrivileges=yes
ProtectSystem=full
ProtectHome=yes
PrivateDevices=yes
PrivateTmp=yes

[Install]
WantedBy=multi-user.target
UNIT

echo "[5/5] Enabling and starting service..."
systemctl daemon-reload
systemctl enable servermanager-agent
systemctl restart servermanager-agent

echo ""
echo "ServerManager Agent installed successfully!"
echo "  Binary: $AGENT_BIN"
echo "  Config: $CONFIG_FILE"
echo "  Service: $SERVICE_FILE"
