#!/usr/bin/env bash
# Usage: curl -fsSL <server>/agents/linux/install-agent.sh | sudo bash -s -- --server "https://your-dashboard" --token "ENROLL_TOKEN"
set -euo pipefail

SERVER_URL=""
ENROLL_TOKEN=""
INTERVAL_MINUTES=30

while [ $# -gt 0 ]; do
  case "$1" in
    --server) SERVER_URL="$2"; shift 2 ;;
    --token) ENROLL_TOKEN="$2"; shift 2 ;;
    --interval) INTERVAL_MINUTES="$2"; shift 2 ;;
    *) echo "Unknown argument: $1"; exit 1 ;;
  esac
done

if [ -z "$SERVER_URL" ] || [ -z "$ENROLL_TOKEN" ]; then
  echo "Usage: install-agent.sh --server <url> --token <enroll_token>" >&2
  exit 1
fi
SERVER_URL="${SERVER_URL%/}"

if [ "$(id -u)" -ne 0 ]; then
  echo "This installer must run as root (use sudo)." >&2
  exit 1
fi

echo "Checking dependencies..."
if ! command -v jq >/dev/null 2>&1; then
  echo "Installing jq..."
  if command -v apt-get >/dev/null 2>&1; then apt-get update -qq && apt-get install -y jq
  elif command -v dnf >/dev/null 2>&1; then dnf install -y jq
  elif command -v yum >/dev/null 2>&1; then yum install -y jq
  else echo "Please install jq manually and re-run." >&2; exit 1
  fi
fi

INSTALL_DIR="/opt/patchline-agent"
CONFIG_DIR="/etc/patchline-agent"
mkdir -p "$INSTALL_DIR" "$CONFIG_DIR"

echo "Downloading agent script..."
curl -fsSL "$SERVER_URL/agents/linux/agent.sh" -o "$INSTALL_DIR/agent.sh"
chmod +x "$INSTALL_DIR/agent.sh"

echo "Enrolling device with dashboard..."
HOSTNAME_VAL=$(hostname)
OS_VERSION=$( [ -f /etc/os-release ] && . /etc/os-release && echo "$PRETTY_NAME" || uname -r )
ARCH=$(uname -m)

ENROLL_RESPONSE=$(curl -fsS -X POST "$SERVER_URL/api/enroll" -H "content-type: application/json" -d "$(jq -n \
  --arg enrollToken "$ENROLL_TOKEN" --arg hostname "$HOSTNAME_VAL" --arg os "linux" \
  --arg osVersion "$OS_VERSION" --arg arch "$ARCH" --arg agentVersion "1.0.0" \
  '{enrollToken:$enrollToken, hostname:$hostname, os:$os, osVersion:$osVersion, arch:$arch, agentVersion:$agentVersion}')")

DEVICE_ID=$(echo "$ENROLL_RESPONSE" | jq -r '.deviceId')
DEVICE_TOKEN=$(echo "$ENROLL_RESPONSE" | jq -r '.deviceToken')

if [ "$DEVICE_ID" = "null" ] || [ -z "$DEVICE_ID" ]; then
  echo "Enrollment failed: $ENROLL_RESPONSE" >&2
  exit 1
fi

jq -n --arg serverUrl "$SERVER_URL" --arg deviceId "$DEVICE_ID" --arg deviceToken "$DEVICE_TOKEN" \
  '{serverUrl:$serverUrl, deviceId:$deviceId, deviceToken:$deviceToken}' > "$CONFIG_DIR/config.json"
chmod 600 "$CONFIG_DIR/config.json"

echo "Registering cron job (every $INTERVAL_MINUTES minutes)..."
CRON_LINE="*/$INTERVAL_MINUTES * * * * root $INSTALL_DIR/agent.sh"
echo "$CRON_LINE" > /etc/cron.d/patchline-agent
chmod 644 /etc/cron.d/patchline-agent

echo "Running first check-in now..."
"$INSTALL_DIR/agent.sh" || true

echo "Done. Device enrolled as $DEVICE_ID."
