#!/usr/bin/env bash
set -euo pipefail

API="https://api.pulse.hlukh.ch"
TOKEN=""
INSTALL=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --api) API="$2"; shift 2;;
    --token) TOKEN="$2"; shift 2;;
    --install) INSTALL=1; shift 1;;
    *) echo "Unknown arg: $1" >&2; exit 1;;
  esac
done

if [[ -z "$TOKEN" ]]; then
  echo "Token is required. Use --token <token>" >&2
  exit 1
fi

API="${API%/}"

disk_info() {
  # disk_free_gb + disk_free_pct for /
  local dfout free_kb total_kb free_gb pct
  dfout=$(df -k / | tail -n 1)
  total_kb=$(echo "$dfout" | awk '{print $2}')
  free_kb=$(echo "$dfout" | awk '{print $4}')
  free_gb=$(python3 - <<PY
t=$free_kb
print(round(t/1024/1024,2))
PY
)
  pct=$(python3 - <<PY
f=$free_kb; t=$total_kb
print(round((f/t)*100,2) if t>0 else None)
PY
)
  echo "\"disk_free_gb\": $free_gb, \"disk_free_pct\": $pct"
}

encryption() {
  if command -v fdesetup >/dev/null 2>&1; then
    local s
    s=$(fdesetup status 2>/dev/null || true)
    if echo "$s" | grep -qi "FileVault is On"; then
      echo "\"encryption_on\": true"
      return
    fi
    if echo "$s" | grep -qi "FileVault is Off"; then
      echo "\"encryption_on\": false"
      return
    fi
  fi
  echo ""
}

backup_age_hours() {
  # Time Machine latest backup age in hours (best effort)
  if command -v tmutil >/dev/null 2>&1; then
    local latest
    latest=$(tmutil latestbackup 2>/dev/null || true)
    if [[ -n "$latest" ]]; then
      # parse timestamp from path: .../YYYY-MM-DD-HHMMSS
      local ts
      ts=$(basename "$latest" | tr '-' ' ' )
      # ts becomes: YYYY MM DD HHMMSS
      local y m d hms hh mm ss
      y=$(echo "$ts" | awk '{print $1}')
      m=$(echo "$ts" | awk '{print $2}')
      d=$(echo "$ts" | awk '{print $3}')
      hms=$(echo "$ts" | awk '{print $4}')
      hh=${hms:0:2}; mm=${hms:2:2}; ss=${hms:4:2}
      # seconds since epoch
      local then now diffh
      then=$(date -j -f "%Y %m %d %H %M %S" "$y $m $d $hh $mm $ss" "+%s" 2>/dev/null || echo "")
      now=$(date "+%s")
      if [[ -n "$then" ]]; then
        diffh=$(( (now-then) / 3600 ))
        echo "\"backup_last_success_hours\": $diffh"
        return
      fi
    fi
  fi
  echo ""
}

payload="$(cat <<JSON
{
  $(disk_info)$( [[ -n "$(encryption)" ]] && echo ", $(encryption)" || true )$( [[ -n "$(backup_age_hours)" ]] && echo ", $(backup_age_hours)" || true )
}
JSON
)"

curl -sS -X POST "$API/api/heartbeat" \
  -H "content-type: application/json" \
  -H "authorization: Bearer $TOKEN" \
  --data "$payload" >/dev/null

echo "[pulse] heartbeat sent"

if [[ "$INSTALL" -eq 1 ]]; then
  PLIST="$HOME/Library/LaunchAgents/ch.hlukh.pulse.plist"
  SCRIPT="$HOME/.local/bin/pulse-agent-macos.sh"
  mkdir -p "$(dirname "$SCRIPT")"
  # copy self to stable location
  cp "$0" "$SCRIPT"
  chmod +x "$SCRIPT"

  cat > "$PLIST" <<PL
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>ch.hlukh.pulse</string>
  <key>ProgramArguments</key>
  <array>
    <string>$SCRIPT</string>
    <string>--api</string><string>$API</string>
    <string>--token</string><string>$TOKEN</string>
  </array>
  <key>StartInterval</key><integer>300</integer>
  <key>RunAtLoad</key><true/>
  <key>StandardOutPath</key><string>$HOME/Library/Logs/pulse-agent.out</string>
  <key>StandardErrorPath</key><string>$HOME/Library/Logs/pulse-agent.err</string>
</dict>
</plist>
PL

  launchctl unload "$PLIST" >/dev/null 2>&1 || true
  launchctl load "$PLIST"
  echo "[pulse] LaunchAgent installed (every 5 min): $PLIST"
fi
