#!/usr/bin/env bash
set -euo pipefail
VERSION="0.2.5c"
CONFIRM_RESTORE="RESTORE_SENTINELOS_BACKGROUND"
CONFIRM_SNAPSHOT="SNAPSHOT_SENTINELOS_BACKGROUND"
DIR="${HOME}/.local/share/sentinelos/background-backups"
DEFAULT="/usr/share/backgrounds/sentinelos/default-desktop.png"

gget() { gsettings get org.mate.background "$1" 2>/dev/null || printf "null"; }
gset() { gsettings set org.mate.background "$1" "$2"; }

snapshot() {
  mkdir -p "$DIR"
  local f="$DIR/$(date +%Y%m%d-%H%M%S)-background.json"
  cat > "$f" <<JSON
{
  "timestamp": "$(date -Iseconds)",
  "draw-background": $(gget draw-background),
  "picture-filename": $(gget picture-filename),
  "picture-options": $(gget picture-options),
  "primary-color": $(gget primary-color),
  "secondary-color": $(gget secondary-color),
  "color-shading-type": $(gget color-shading-type)
}
JSON
  echo "$f"
}

summary() {
  cat <<EOF
SentinelOS Background Preservation Guard
version: $VERSION
default_background: $DEFAULT
default_background_state: $([ -f "$DEFAULT" ] && echo present || echo missing)
policy: theme tools must not modify wallpaper/background keys
backup_dir: $DIR
current_picture: $(gget picture-filename)
current_options: $(gget picture-options)
EOF
}

verify() {
  local ok=1
  [ -f "$DEFAULT" ] || { echo "missing: $DEFAULT"; ok=0; }
  gsettings list-schemas | grep -qx org.mate.background || { echo "missing schema: org.mate.background"; ok=0; }
  [ "$ok" = "1" ] && echo "verify: ok" || { echo "verify: failed"; exit 1; }
}

restore_default() {
  local confirm="${1:-}"
  if [ "$(id -u)" = "0" ]; then echo "ERROR: run as desktop user, not root"; exit 2; fi
  if [ "$confirm" != "$CONFIRM_RESTORE" ]; then echo "ERROR: use --confirm $CONFIRM_RESTORE"; exit 2; fi
  [ -f "$DEFAULT" ] || { echo "ERROR: missing $DEFAULT"; exit 1; }
  local s; s=$(snapshot)
  gset draw-background true
  gset picture-filename "$DEFAULT"
  gset picture-options "zoom"
  echo "backup: $s"
  echo "restored: $DEFAULT"
  echo "picture-options: zoom"
}

case "${1:-}" in
  --summary) summary ;;
  --verify) verify ;;
  --current) summary ;;
  --snapshot)
    shift; [ "${1:-}" = "--confirm" ] && [ "${2:-}" = "$CONFIRM_SNAPSHOT" ] || { echo "ERROR: use --confirm $CONFIRM_SNAPSHOT"; exit 2; }
    echo "backup: $(snapshot)"
    ;;
  --restore-default)
    shift; [ "${1:-}" = "--confirm" ] && restore_default "${2:-}" || { echo "ERROR: use --confirm $CONFIRM_RESTORE"; exit 2; }
    ;;
  *)
    cat <<EOF
sentinelos-background-guard v$VERSION
  --summary
  --verify
  --snapshot --confirm $CONFIRM_SNAPSHOT
  --restore-default --confirm $CONFIRM_RESTORE
EOF
    ;;
esac
