#!/bin/bash
# aria-run-wrapper.sh — wraps a service command, emits structured JSONL run-record.
# Adapted from Paperclip's run-record schema (10.05.2026).
#
# Usage from systemd unit:
#   ExecStart=/root/aria/scripts/aria-run-wrapper.sh <service-name> <command> [args...]
#
# Output line schema (one JSON object per line, append-only):
#   {
#     "run_id":     "<uuidgen>",
#     "service":    "<service-name>",
#     "host":       "<hostname>",
#     "started_at": "<ISO-8601 UTC>",
#     "ended_at":   "<ISO-8601 UTC>",
#     "duration_s": <float>,
#     "status":     "ok" | "fail",
#     "exit_code":  <int>,
#     "command":    "<short cmd basename>"
#   }
#
# Invariants:
#   - Wrapper exit code matches wrapped command exit code (systemd sees the truth).
#   - JSONL line is always written, even on failure (atomic via tee).
#   - No dependencies beyond coreutils + python3 stdlib (json.dumps for safe escaping).

set -uo pipefail

LOG_FILE="${ARIA_RUN_LOG:-/var/log/aria-runs.jsonl}"

if [[ $# -lt 2 ]]; then
  echo "usage: $0 <service-name> <command> [args...]" >&2
  exit 64
fi

SERVICE="$1"; shift
CMD_BASENAME="$(basename "$1")"

run_id="$(cat /proc/sys/kernel/random/uuid 2>/dev/null || python3 -c 'import uuid;print(uuid.uuid4())')"
hostname="$(hostname -s 2>/dev/null || echo unknown)"
started_at="$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)"
started_epoch="$(date +%s.%3N)"

# Run the wrapped command, propagate stdout/stderr verbatim.
"$@"
exit_code=$?

ended_at="$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)"
ended_epoch="$(date +%s.%3N)"
duration_s="$(awk -v s="$started_epoch" -v e="$ended_epoch" 'BEGIN{printf "%.3f", e-s}')"

if [[ $exit_code -eq 0 ]]; then
  status="ok"
else
  status="fail"
fi

# Build JSON via python3 to escape correctly (service names may contain dashes; safe enough today,
# but stays correct if future service names get unusual chars).
python3 - "$run_id" "$SERVICE" "$hostname" "$started_at" "$ended_at" "$duration_s" "$status" "$exit_code" "$CMD_BASENAME" <<'PY' >> "$LOG_FILE"
import json, sys
run_id, service, host, started_at, ended_at, duration_s, status, exit_code, cmd = sys.argv[1:]
print(json.dumps({
    "run_id":     run_id,
    "service":    service,
    "host":       host,
    "started_at": started_at,
    "ended_at":   ended_at,
    "duration_s": float(duration_s),
    "status":     status,
    "exit_code":  int(exit_code),
    "command":    cmd,
}, ensure_ascii=False))
PY

exit $exit_code
