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

NODE_ID=${1:?node id required}
NODE_ALIAS=${2:?ssh alias required}
SSH_CONFIG=${SSH_CONFIG:-/etc/guanghu/nodes/ssh/config}
RECEIPT_DIR=${RECEIPT_DIR:-/var/lib/guanghu/receipts}

remote=$(ssh -F "$SSH_CONFIG" -o BatchMode=yes -o ConnectTimeout=8 "$NODE_ALIAS" '
  set -e
  gatekeeper=null
  for port in 3911 3910; do
    if curl -fsS --max-time 2 "http://127.0.0.1:$port/health" >/tmp/guanghu-node-health.json 2>/dev/null; then
      gatekeeper=$(jq -c "{ok,service,version,auth_mode}" /tmp/guanghu-node-health.json 2>/dev/null || echo "{\"ok\":true}")
      break
    fi
  done
  rm -f /tmp/guanghu-node-health.json
  jq -n --arg hostname "$(hostname)" --arg disk_used "$(df --output=pcent / | tail -1 | tr -d " ")" \
    --arg uptime_seconds "$(cut -d. -f1 /proc/uptime)" --argjson gatekeeper "${gatekeeper:-null}" \
    "{hostname:\$hostname,disk_used:\$disk_used,uptime_seconds:(\$uptime_seconds|tonumber),gatekeeper:\$gatekeeper}"
')

install -d -m 0750 -o root -g guanghu "$RECEIPT_DIR"
target="$RECEIPT_DIR/$NODE_ID-latest.json"
tmp=$(mktemp "$target.XXXXXX")
trap 'rm -f "$tmp"' EXIT
jq -n --arg node_id "$NODE_ID" --arg checked_at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --argjson remote "$remote" \
  '{schema:"guanghu.node-heartbeat/v1",ok:true,node_id:$node_id,checked_at:$checked_at,remote:$remote}' > "$tmp"
install -m 0640 -o root -g guanghu "$tmp" "$target"
cat "$target"
