#!/usr/bin/env bash
# Togen signage agent heartbeat (DVI-1201 / DVI-1191 P4b).
# Run every ~30s by togen-signage-checkin.timer. Reports host facts to
# POST <host>/signage/checkin so Admin -> Agents -> Display shows online status.
set -euo pipefail

CONF=/etc/togen-signage/agent.conf
TOKEN_FILE=/etc/togen-signage/agent.token
AGENT_VERSION="1.0.0"

if [ -f "$CONF" ]; then
  # shellcheck disable=SC1090
  . "$CONF"
fi
: "${TOGEN_HOST:?TOGEN_HOST not set in $CONF}"

if [ ! -f "$TOKEN_FILE" ]; then
  echo "agent token missing at $TOKEN_FILE" >&2
  exit 1
fi
AGENT_TOKEN=$(cat "$TOKEN_FILE")

hostname_val=$(hostname)
local_ip=$(ip route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if ($i=="src") print $(i+1)}' | head -n1 || true)
public_ip=$(curl -fsS --max-time 3 https://api.ipify.org 2>/dev/null || true)
screen_res=$(DISPLAY=:0 xrandr --current 2>/dev/null | awk '/\*/{print $1; exit}' || true)

body=$(cat <<JSON
{"hostname":"$hostname_val","local_ip":"$local_ip","public_ip":"$public_ip","agent_version":"$AGENT_VERSION","screen":"$screen_res"}
JSON
)

resp=$(curl -sS -w '\n%{http_code}' -X POST "$TOGEN_HOST/signage/checkin" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H 'Content-Type: application/json' \
  -d "$body")
code=$(printf '%s\n' "$resp" | tail -n1)
respbody=$(printf '%s\n' "$resp" | sed '$d')

if [ "$code" = "200" ]; then
  exit 0
fi

echo "checkin failed (HTTP $code): $respbody" >&2
exit 1
