#!/usr/bin/env sh
# Sextant module — generic reference reporter.
#
# Reports your server's REAL online count to sextant.gg, signed with your
# server's secret. Works for any server (Ragnarok/rAthena, custom L2, …): the
# only thing that changes is how you read the count. Run it every 5 minutes,
# e.g. from cron:   */5 * * * *  /path/to/sextant-report.sh
#
# Needs: sh, openssl, curl (all standard).

# ---- fill these in --------------------------------------------------------
SERVER_REF="YOUR-SERVER-SLUG"          # e.g. muhro  (your server's slug on sextant.gg)
API_SECRET="YOUR-API-SECRET"           # Account -> your server -> module secret
# COUNT_CMD must print your current online player count on stdout. Examples:
#   rAthena/Hercules (MySQL):  mysql -N -uUSER -pPASS ragnarok -e "SELECT COUNT(*) FROM char WHERE online=1"
#   L2J (MySQL):               mysql -N -uUSER -pPASS l2jdb    -e "SELECT COUNT(*) FROM characters WHERE online=1"
COUNT_CMD='echo 0'
# ---------------------------------------------------------------------------

ENDPOINT="https://sextant.gg/api/module/report"

PLAYERS=$(eval "$COUNT_CMD" | tr -dc '0-9')
[ -z "$PLAYERS" ] && { echo "sextant: could not read online count" >&2; exit 1; }

BODY="{\"players\":$PLAYERS}"
TS=$(date +%s000)                       # unix milliseconds (seconds * 1000 is fine)
SIG=$(printf '%s' "$TS.$BODY" | openssl dgst -sha256 -hmac "$API_SECRET" | sed 's/^.*= //')

curl -fsS -X POST "$ENDPOINT" \
  -H "content-type: application/json" \
  -H "x-sextant-server: $SERVER_REF" \
  -H "x-sextant-timestamp: $TS" \
  -H "x-sextant-signature: $SIG" \
  -d "$BODY"
