#!/usr/bin/env bash
set -euo pipefail

CONFIG="/etc/cyan-skillfish-governor-smu/config.toml"
BACKUP_DIR="/etc/cyan-skillfish-governor-smu/backups"
LAST_BACKUP="/etc/cyan-skillfish-governor-smu/.bc250-40cu-last-backup"
SERVICE="cyan-skillfish-governor-smu.service"

usage() {
  cat <<'EOF'
BC-250 governor profile helper

Usage:
  bc250-governor-profile sweet-spot
  bc250-governor-profile restore
  bc250-governor-profile status

Commands:
  sweet-spot  Backup the current config and apply a 1500 MHz / 900 mV cap.
  restore     Restore the last config backed up by this helper.
  status      Show current governor config and service status.
EOF
}

need_root() {
  if [ "$(id -u)" != "0" ]; then
    echo "ERROR: this command must run as root." >&2
    exit 1
  fi
}

restart_service() {
  if systemctl list-unit-files "$SERVICE" >/dev/null 2>&1; then
    systemctl restart "$SERVICE" || {
      echo "WARN: could not restart $SERVICE. Check: systemctl status $SERVICE" >&2
      return 1
    }
  fi
}

write_sweet_spot_config() {
  cat > "$CONFIG" <<'EOF'
# BC-250 40CU conservative profile.
# Generated by bc250-governor-profile sweet-spot.
# Target: 1500 MHz / 900 mV, based on bc250-40cu-unlock thermal guidance.

[timing.intervals]
sample = 250
adjust = 100_000

[gpu-usage]
fix-metrics = true
method = "busy-flag"
flush-every = 10

[gpu]
set-method = "smu"

[dbus]
enabled = true

[frequency-range]
min = 1000
max = 1500

[timing.ramp-rates]
normal = 1
burst = 50

[timing]
burst-samples = 60
down-events = 5

[frequency-thresholds]
adjust = 10

[load-target]
upper = 0.65
lower = 0.50

[temperature]
throttling = 85
throttling_recovery = 75

[[safe-points]]
frequency = 500
voltage = 700

[[safe-points]]
frequency = 1000
voltage = 800

[[safe-points]]
frequency = 1175
voltage = 850

[[safe-points]]
frequency = 1500
voltage = 900
EOF
}

apply_sweet_spot() {
  need_root
  mkdir -p "$BACKUP_DIR" "$(dirname "$CONFIG")"

  if [ -f "$CONFIG" ]; then
    backup="$BACKUP_DIR/config.toml.$(date +%Y%m%d-%H%M%S).bak"
    cp -a "$CONFIG" "$backup"
    printf '%s\n' "$backup" > "$LAST_BACKUP"
    echo "Backed up current governor config to $backup"
  else
    echo "No existing governor config found at $CONFIG; writing a new one."
  fi

  write_sweet_spot_config
  echo "Applied BC-250 40CU sweet spot profile: 1500 MHz / 900 mV."
  restart_service || true
}

restore_config() {
  need_root

  if [ ! -f "$LAST_BACKUP" ]; then
    echo "ERROR: no backup marker found at $LAST_BACKUP." >&2
    echo "Available backups:" >&2
    ls -1 "$BACKUP_DIR"/config.toml.*.bak 2>/dev/null || true
    exit 1
  fi

  backup="$(cat "$LAST_BACKUP")"
  if [ ! -f "$backup" ]; then
    echo "ERROR: backup no longer exists: $backup" >&2
    exit 1
  fi

  cp -a "$backup" "$CONFIG"
  echo "Restored governor config from $backup"
  restart_service || true
}

show_status() {
  if [ -f "$CONFIG" ]; then
    echo "Governor config: $CONFIG"
    grep -E '^(min|max|frequency|voltage|fix-metrics|method|set-method|throttling)' "$CONFIG" || true
  else
    echo "Governor config not found at $CONFIG"
  fi
  echo
  systemctl status "$SERVICE" --no-pager || true
}

case "${1:-}" in
  sweet-spot) apply_sweet_spot ;;
  restore) restore_config ;;
  status) show_status ;;
  -h|--help|help|"") usage ;;
  *)
    usage >&2
    exit 2
    ;;
esac
