#!/bin/sh
# Mirqat agent installer.  Outbound-only, read-only on the host.
#   curl -fsSL https://mirqat.dev/install.sh | sh -s -- --token mq_enroll_XXXX
#
# Installs a tiny POSIX-sh collector that pushes disk/CPU/RAM/load to the
# Mirqat ingest endpoint every 30s. No inbound ports, no SSH keys.
set -eu

MIRQAT_URL="${MIRQAT_URL:-https://mirqat.dev}"
TOKEN="${MIRQAT_TOKEN:-}"
INTERVAL="${MIRQAT_INTERVAL:-30}"

while [ $# -gt 0 ]; do
  case "$1" in
    --token) TOKEN="$2"; shift 2 ;;
    --url)   MIRQAT_URL="$2"; shift 2 ;;
    --interval) INTERVAL="$2"; shift 2 ;;
    *) shift ;;
  esac
done

if [ -z "$TOKEN" ]; then
  echo "mirqat: missing --token (get one from the app - Add - Install agent)" >&2
  exit 1
fi

DIR=/opt/mirqat-agent
echo "mirqat: installing agent -> $DIR (ingest: $MIRQAT_URL)"
mkdir -p "$DIR"

# -- enroll: exchange the one-time token for a per-agent credential ----------
OS="$(uname -s) $(uname -m)"
ENROLL="$(curl -fsSL -X POST "$MIRQAT_URL/api/enroll" \
  -H 'content-type: application/json' \
  -d "{\"token\":\"$TOKEN\",\"os\":\"$OS\",\"agent_version\":\"1.4.2\"}" || true)"
AGENT_TOKEN="$(printf '%s' "$ENROLL" | sed -n 's/.*"agent_token":"\([^"]*\)".*/\1/p')"
[ -z "$AGENT_TOKEN" ] && AGENT_TOKEN="$TOKEN"   # ingest also accepts the enroll token

cat > "$DIR/agent.conf" <<EOF
MIRQAT_URL=$MIRQAT_URL
AGENT_TOKEN=$AGENT_TOKEN
INTERVAL=$INTERVAL
EOF

# -- the collector -----------------------------------------------------------
cat > "$DIR/agent.sh" <<'AGENT'
#!/bin/sh
set -eu
. /opt/mirqat-agent/agent.conf

cpu_sample() { awk '/^cpu /{print $2+$3+$4+$5+$6+$7+$8, $2+$3+$4+$7+$8}' /proc/stat; }

read_cpu() {
  set -- $(cpu_sample); T1=$1; B1=$2
  sleep 1
  set -- $(cpu_sample); T2=$1; B2=$2
  DT=$((T2 - T1)); DB=$((B2 - B1))
  if [ "$DT" -gt 0 ]; then echo $(( (DB * 100) / DT )); else echo 0; fi
}

collect() {
  DISK=$(df -P / 2>/dev/null | awk 'NR==2{gsub("%","",$5); print $5}'); DISK=${DISK:-0}
  MEM=$(awk '/MemTotal/{t=$2} /MemAvailable/{a=$2} END{ if(t>0) printf "%d",(t-a)*100/t; else print 0 }' /proc/meminfo 2>/dev/null); MEM=${MEM:-0}
  SWAP=$(awk '/SwapTotal/{t=$2} /SwapFree/{f=$2} END{ if(t>0) printf "%d",(t-f)*100/t; else print 0 }' /proc/meminfo 2>/dev/null); SWAP=${SWAP:-0}
  set -- $(cat /proc/loadavg 2>/dev/null); L1=${1:-0}; L5=${2:-0}; L15=${3:-0}
  UP=$(awk '{printf "%d",$1}' /proc/uptime 2>/dev/null); UP=${UP:-0}
  CPU=$(read_cpu)
  printf '{"cpu_pct":%s,"ram_pct":%s,"swap_pct":%s,"disk_pct":%s,"disk_mount":"/","load1":%s,"load5":%s,"load15":%s,"uptime_s":%s,"agent_version":"1.4.2"}' \
    "$CPU" "$MEM" "$SWAP" "$DISK" "$L1" "$L5" "$L15" "$UP"
}

echo "mirqat-agent: reporting to $MIRQAT_URL every ${INTERVAL}s"
while true; do
  BODY=$(collect)
  curl -fsS -X POST "$MIRQAT_URL/api/ingest" \
    -H "authorization: Bearer $AGENT_TOKEN" \
    -H 'content-type: application/json' \
    -d "$BODY" >/dev/null 2>&1 || echo "mirqat-agent: push failed (will retry)"
  sleep "$INTERVAL"
done
AGENT
chmod +x "$DIR/agent.sh"

# -- run it (systemd if available, else nohup) -------------------------------
if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
  cat > /etc/systemd/system/mirqat-agent.service <<EOF
[Unit]
Description=Mirqat Agent
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/bin/sh /opt/mirqat-agent/agent.sh
Restart=always
RestartSec=5
Nice=10

[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload
  systemctl enable --now mirqat-agent >/dev/null 2>&1 || systemctl restart mirqat-agent
  echo "mirqat: agent running as systemd service (systemctl status mirqat-agent)"
else
  pkill -f /opt/mirqat-agent/agent.sh 2>/dev/null || true
  nohup /bin/sh "$DIR/agent.sh" >/var/log/mirqat-agent.log 2>&1 &
  echo "mirqat: agent running (nohup, log: /var/log/mirqat-agent.log)"
fi

echo "mirqat: done - your meerkat is taking post. Watch the colony at $MIRQAT_URL/app"
