#!/usr/bin/env bash
# run_audit_playbook.sh — bundle audit restore → config patch → gateway restart → verification.
set -euo pipefail

WORKSPACE="/home/isthekid/.openclaw/workspace"
CONFIG="/home/isthekid/.openclaw/openclaw.json"
HEARTBEAT_SCRIPT="$WORKSPACE/bin/heartbeat_helper.sh"
HEARTBEAT_LABEL=${HEARTBEAT_LABEL:-"audit playbook"}
HEARTBEAT_PID=""

log() {
  printf '\n[%s] %s\n' "$(date --iso-8601=seconds)" "$1"
}

show_usage() {
  cat <<'EOF'
Usage: run_audit_playbook.sh

Steps:
  1. Validate WORKFLOW_AUTO.md + daily memory present
  2. Apply pending config patch script (edit openclaw.json as needed)
  3. Validate JSON syntax
  4. Restart gateway via systemctl --user restart openclaw-gateway
  5. Confirm status + tail journal

Prereqs:
  - Run from /home/isthekid/.openclaw/workspace (or adjust paths)
  - Provide patch logic inside inner section before JSON validation
EOF
}

if [[ ${1:-} == "--help" ]]; then
  show_usage
  exit 0
fi

if [[ -x "$HEARTBEAT_SCRIPT" ]]; then
  "$HEARTBEAT_SCRIPT" "$HEARTBEAT_LABEL" &
  HEARTBEAT_PID=$!
  trap 'if [[ -n "$HEARTBEAT_PID" ]]; then kill "$HEARTBEAT_PID" 2>/dev/null || true; fi' EXIT
fi

log "Ensuring WORKFLOW_AUTO.md + daily memory exist"
ls "$WORKSPACE/WORKFLOW_AUTO.md" "$WORKSPACE/memory" >/dev/null

log "TODO: apply config patch here if needed (manual edit placeholder)"
# Example: use python3 or jq to patch config.
# python3 - <<'PY'
# import json, pathlib
# path = pathlib.Path("/home/isthekid/.openclaw/openclaw.json")
# data = json.loads(path.read_text())
# ... modify data ...
# path.write_text(json.dumps(data, indent=2) + "\n")
# PY

log "Validating JSON syntax"
python3 -m json.tool "$CONFIG" >/tmp/openclaw.json.pretty

log "Restarting gateway"
systemctl --user restart openclaw-gateway
sleep 3

log "Gateway status"
systemctl --user status openclaw-gateway --no-pager | head -40

log "Recent journal"
journalctl --user -u openclaw-gateway --since "5 min ago" --no-pager | tail -40

log "Playbook completed"
