#!/usr/bin/env bash
# Polls the TiltBridge's live JSON endpoint and appends one line per Tilt
# color to history/<Color>.jsonl. Safe to run every N minutes via cron.
#
# Deploy: copy this whole brew-dashboard/ folder to the server, then add
# a crontab entry (see README.md), e.g.:
#   */5 * * * * /path/to/brew-dashboard/poll_tiltbridge.sh >> /path/to/brew-dashboard/poll.log 2>&1

set -euo pipefail

TILTBRIDGE_URL="http://192.168.1.171/api/json/"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HISTORY_DIR="${SCRIPT_DIR}/history"

mkdir -p "$HISTORY_DIR"

TS="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

DATA="$(curl -sf -m 10 "$TILTBRIDGE_URL")" || {
  echo "[$TS] ERROR: could not reach TiltBridge at $TILTBRIDGE_URL" >&2
  exit 1
}

# The device returns an array, one object per active Tilt. Tag each with our
# own poll timestamp (device doesn't include one) and append to that color's
# file. Numeric fields arrive as strings from the device; cast them here so
# every downstream consumer (the dashboard) can rely on real numbers.
echo "$DATA" | jq -c --arg ts "$TS" '
  .[] | {
    ts: $ts,
    color: .color,
    tempC: (if .tempUnit == "F" then ((.temp|tonumber) - 32) * 5 / 9 else (.temp|tonumber) end),
    tempRaw: (.temp|tonumber),
    tempUnit: .tempUnit,
    sg: (.calibratedGravity|tonumber),
    sgUncalibrated: (.uncalibratedGravity|tonumber),
    rssi: .rssi,
    battery_weeks: .weeks_on_battery,
    fwVersion: .fwVersion
  }
' | while IFS= read -r line; do
  color="$(echo "$line" | jq -r '.color')"
  if [ -z "$color" ] || [ "$color" = "null" ]; then
    continue
  fi
  echo "$line" >> "${HISTORY_DIR}/${color}.jsonl"
done

echo "[$TS] OK"
