#!/bin/bash
# ServerManager Monitoring Agent
# This script runs as a systemd service on monitored servers.
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() {
    local payload
    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"
    echo "Server: $SERVER_URL"
    echo "Interval: ${INTERVAL}s"

    sleep 5

    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
