#!/bin/sh
set -eu

unit="${NOVIJ_TRAFFIC_UNIT:-novij-storage.slice}"
data_dir="${NOVIJ_TRAFFIC_DATA_DIR:-/var/lib/novij/storage/traffic}"
history_file="$data_dir/hourly.jsonl"

counter() {
  value="$(systemctl show "$unit" --property="$1" --value 2>/dev/null || true)"
  case "$value" in
    ''|*[!0-9]*) printf '0' ;;
    *) printf '%s' "$value" ;;
  esac
}

sample() {
  timestamp="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
  ingress="$(counter IPIngressBytes)"
  egress="$(counter IPEgressBytes)"
  printf '{"schema":"novij.traffic.sample.v1","timestamp":"%s","project":"storage","unit":"%s","ingress_bytes":%s,"egress_bytes":%s}' \
    "$timestamp" "$unit" "$ingress" "$egress"
}

snapshot() {
  umask 027
  install -d -m 0750 "$data_dir"
  sample >>"$history_file"
  printf '\n' >>"$history_file"
}

status() {
  host='null'
  if command -v vnstat >/dev/null 2>&1; then
    candidate="$(vnstat --json 2>/dev/null | tr -d '\r\n' || true)"
    case "$candidate" in
      \{*) host="$candidate" ;;
    esac
  fi
  printf '{"schema":"novij.traffic.status.v1","service":%s,"host":%s}\n' "$(sample)" "$host"
}

case "${1:-status}" in
  snapshot) snapshot ;;
  status) status ;;
  history)
    [ -f "$history_file" ] || exit 0
    exec tail -n "${NOVIJ_TRAFFIC_HISTORY_LINES:-168}" "$history_file"
    ;;
  *)
    echo "usage: novij-storage-traffic {status|snapshot|history}" >&2
    exit 2
    ;;
esac
