#!/usr/bin/env bash
# =============================================
#  MinusNow Monitoring Agent Installer (Linux) v2.5
#  February 2026
# =============================================
# Registers the host to MinusNow and installs a systemd timer for heartbeats.
# Collects system metrics (CPU, memory, disk, uptime) and sends them to the server.
#
# Usage:
#   sudo ./agent-install-linux.sh --server https://minusnow.example.com --org ORG001
#   sudo ./agent-install-linux.sh --server http://192.168.1.10:5000 --org ORG001 --asset-id WEB-SVR-01 --interval 5

set -euo pipefail

SERVER=""
ORG_ID=""
ASSET_ID=""
INTERVAL=1   # minutes

while [[ $# -gt 0 ]]; do
  case "$1" in
    --server)   SERVER="$2"; shift 2 ;;
    --org)      ORG_ID="$2"; shift 2 ;;
    --asset-id) ASSET_ID="$2"; shift 2 ;;
    --interval) INTERVAL="$2"; shift 2 ;;
    -h|--help)
      echo "Usage: sudo $0 --server https://... --org <ORG_ID> [--asset-id <ID>] [--interval <minutes>]"
      exit 0 ;;
    *) echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

if [[ -z "$SERVER" || -z "$ORG_ID" ]]; then
  echo "Error: --server and --org are required" >&2
  exit 1
fi

[[ -z "$ASSET_ID" ]] && ASSET_ID=$(hostname -f 2>/dev/null || hostname)

if [[ $(id -u) -ne 0 ]]; then
  echo "Error: run as root (sudo) to install systemd timer" >&2
  exit 1
fi

if ! command -v curl >/dev/null 2>&1; then
  echo "Error: curl is required (apt install -y curl)" >&2
  exit 1
fi

echo ""
echo "==> MinusNow Agent Installer (Linux) v2.5"

CONFIG_DIR="/etc/minusnow"
BIN_PATH="/usr/local/bin/minusnow-agent.sh"
SERVICE_NAME="minusnow-agent"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
TIMER_FILE="/etc/systemd/system/${SERVICE_NAME}.timer"

mkdir -p "$CONFIG_DIR"

# Save config
cat > "${CONFIG_DIR}/agent.conf" <<EOF
SERVER=${SERVER}
ORG_ID=${ORG_ID}
ASSET_ID=${ASSET_ID}
AGENT_VERSION=2.5
INTERVAL_MIN=${INTERVAL}
INSTALLED_AT=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
EOF
echo "    Config saved: ${CONFIG_DIR}/agent.conf"

# Create agent script with system metrics
cat > "$BIN_PATH" <<'SCRIPT'
#!/usr/bin/env bash
set -euo pipefail

CONFIG_FILE="/etc/minusnow/agent.conf"
[[ ! -f "$CONFIG_FILE" ]] && { echo "Missing config: $CONFIG_FILE" >&2; exit 1; }
source "$CONFIG_FILE"

[[ -z "${SERVER:-}" || -z "${ORG_ID:-}" || -z "${ASSET_ID:-}" ]] && { echo "Invalid config" >&2; exit 1; }

# Collect system metrics
CPU_PCT=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' 2>/dev/null || echo "0")
MEM_PCT=$(free | awk '/Mem:/ {printf("%.1f", $3/$2 * 100)}' 2>/dev/null || echo "0")
DISK_PCT=$(df -h / | awk 'NR==2 {gsub(/%/,""); print $5}' 2>/dev/null || echo "0")
UPTIME_HRS=$(awk '{printf("%.1f", $1/3600)}' /proc/uptime 2>/dev/null || echo "0")
HOSTNAME_VAL=$(hostname -f 2>/dev/null || hostname)

payload=$(cat <<JSON
{
  "assetId": "${ASSET_ID}",
  "orgId": "${ORG_ID}",
  "agentVersion": "${AGENT_VERSION:-2.5}",
  "metrics": {
    "cpuPercent": ${CPU_PCT},
    "memPercent": ${MEM_PCT},
    "diskPercent": ${DISK_PCT},
    "uptimeHours": ${UPTIME_HRS},
    "hostname": "${HOSTNAME_VAL}",
    "os": "Linux",
    "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
  }
}
JSON
)

curl -fsS -X POST "${SERVER%/}/api/agent/register" -H 'Content-Type: application/json' -d "$payload" >/dev/null 2>&1 || true
curl -fsS -X POST "${SERVER%/}/api/agent/heartbeat" -H 'Content-Type: application/json' -d "$payload" >/dev/null 2>&1 || true
SCRIPT

chmod +x "$BIN_PATH"

# Create systemd service and timer
if command -v systemctl >/dev/null 2>&1; then
  cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=MinusNow Monitoring Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=$BIN_PATH
EOF

  cat > "$TIMER_FILE" <<EOF
[Unit]
Description=MinusNow Agent Heartbeat Timer

[Timer]
OnBootSec=30s
OnUnitActiveSec=${INTERVAL}min

[Install]
WantedBy=timers.target
EOF

  systemctl daemon-reload
  systemctl enable --now "${SERVICE_NAME}.timer"
else
  echo "    [WARN] systemd not found. Set up a cron job manually."
fi

# Initial run
"$BIN_PATH" || true

echo ""
echo "    [OK] Agent installed successfully"
echo "    Asset:    $ASSET_ID"
echo "    Org:      $ORG_ID"
echo "    Server:   $SERVER"
echo "    Interval: Every ${INTERVAL} minute(s)"
echo "    Config:   ${CONFIG_DIR}/agent.conf"
echo ""
