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

NODE_ID=${NODE_ID:-BS-GZ-006}
NODE_ALIAS=${NODE_ALIAS:-bs-gz-006}
SSH_CONFIG=${SSH_CONFIG:-/etc/guanghu/nodes/ssh/config}
RECEIPT_FILE=${RECEIPT_FILE:-/var/lib/guanghu/receipts/BS-GZ-006-latest.json}
FRONT_DOOR_URL=${FRONT_DOOR_URL:-https://guanghulab.com/}
APP_HUB_URL=${APP_HUB_URL:-https://guanghulab.com/jd/api/status}

remote=$(ssh -F "$SSH_CONFIG" -o BatchMode=yes "$NODE_ALIAS" \
  "set -e; jq -n \
    --arg hostname \"\$(hostname)\" \
    --arg nginx \"\$(systemctl is-active nginx)\" \
    --arg tunnel \"\$(systemctl is-active guanghu-jd-web-tunnel.service)\" \
    --arg disk_used \"\$(df --output=pcent / | tail -1 | tr -d ' ')\" \
    --arg uptime_seconds \"\$(cut -d. -f1 /proc/uptime)\" \
    '{hostname:\$hostname,nginx:\$nginx,tunnel:\$tunnel,disk_used:\$disk_used,uptime_seconds:(\$uptime_seconds|tonumber)}'")

front_status=$(curl -fsS -o /dev/null -w '%{http_code}' "$FRONT_DOOR_URL")
hub=$(curl -fsS "$APP_HUB_URL")
tmp=$(mktemp "${RECEIPT_FILE}.XXXXXX")
trap 'rm -f "$tmp"' EXIT

jq -n \
  --arg node_id "$NODE_ID" \
  --arg checked_at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
  --arg front_status "$front_status" \
  --argjson remote "$remote" \
  --argjson hub "$hub" \
  '{schema:"guanghu.node-heartbeat/v1",ok:true,node_id:$node_id,checked_at:$checked_at,front_door_http:($front_status|tonumber),remote:$remote,jd_hub:{ok:$hub.ok,node_id:$hub.node_id,service:$hub.service}}' \
  > "$tmp"
install -m 0640 -o root -g guanghu "$tmp" "$RECEIPT_FILE"
cat "$RECEIPT_FILE"
