#!/bin/bash
# Installer self-contained du backup restic Mac de Léna
# À copier-coller dans le Terminal du Mac de Léna (user: lena)

set -uo pipefail

if [ "$(whoami)" != "lena" ]; then
  echo "ERREUR: lance ce script en tant que 'lena' (current: $(whoami))"; exit 1
fi

CONFIG_DIR="$HOME/.config/lena-backup"
LAUNCH_DIR="$HOME/Library/LaunchAgents"
LOG_DIR="$HOME/Library/Logs/lena-backup"
mkdir -p "$CONFIG_DIR" "$LAUNCH_DIR" "$LOG_DIR"

# 1) Restic
if ! command -v restic >/dev/null; then
  if ! command -v brew >/dev/null; then
    echo "Installe Homebrew d'abord : https://brew.sh"; exit 2
  fi
  brew install restic
fi
restic version

# 2) Excludes
cat > "$CONFIG_DIR/excludes.txt" <<'EOF'
**/.Trash
**/.Trashes
**/Library/Caches
**/Library/Application Support/CrashReporter
**/Library/Application Support/MobileSync/Backup
**/Library/Developer/Xcode/DerivedData
**/Library/Developer/CoreSimulator/Caches
**/Library/Logs/DiagnosticReports
**/Library/Containers/*/Data/Library/Caches
**/Library/Group Containers/*/Library/Caches
.DS_Store
.fseventsd
.Spotlight-V100
.TemporaryItems
.DocumentRevisions-V100
.PKInstallSandboxManager
.PKInstallSandboxManager-SystemSoftware
.com.apple.timemachine.donotpresent
**/node_modules
**/.npm
**/.cache
**/.gradle
**/.m2/repository
**/__pycache__
**/.venv
**/venv
**/target
**/build
**/dist
**/Library/Photos/Libraries/*/resources/derivatives
**/Library/Photos/Libraries/*/resources/cpl
Library/Mobile Documents
EOF

# 3) Script de backup
cat > "$CONFIG_DIR/lena-backup.sh" <<'EOF'
#!/bin/bash
set -uo pipefail
LOG="$HOME/Library/Logs/lena-backup/lena-backup.log"
log(){ echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG"; }

PWHT=$(security find-generic-password -a lena -s lena-backup-htpasswd -w 2>/dev/null) || { log "ERR keychain htpasswd"; exit 2; }
PWRE=$(security find-generic-password -a lena -s lena-backup-restic   -w 2>/dev/null) || { log "ERR keychain restic"; exit 2; }
export RESTIC_REPOSITORY="rest:https://lena:${PWHT}@backup.technotrement.com/lena"
export RESTIC_PASSWORD="$PWRE"

log "=== backup ==="
restic backup --tag auto --exclude-file="$HOME/.config/lena-backup/excludes.txt" --exclude-caches --one-file-system "$HOME" 2>&1 | tee -a "$LOG"
RC=${PIPESTATUS[0]}
if [ $RC -ne 0 ]; then
  log "ERR backup exit=$RC"
  curl -s -d "Backup Léna ECHEC (exit=$RC)" -H "Title: Backup Léna KO" -H "Tags: warning" https://ntfy.technotrement.com/lena-backup >/dev/null
  exit $RC
fi

log "=== prune ==="
restic forget --keep-hourly 24 --keep-daily 14 --keep-weekly 8 --keep-monthly 12 --prune 2>&1 | tee -a "$LOG"
log "=== ok ==="
EOF
chmod +x "$CONFIG_DIR/lena-backup.sh"

# 4) LaunchAgent
PLIST="$LAUNCH_DIR/com.technotrement.lena-backup.plist"
cat > "$PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>com.technotrement.lena-backup</string>
  <key>ProgramArguments</key><array><string>$CONFIG_DIR/lena-backup.sh</string></array>
  <key>StartInterval</key><integer>3600</integer>
  <key>RunAtLoad</key><true/>
  <key>StandardOutPath</key><string>$LOG_DIR/launchd.out</string>
  <key>StandardErrorPath</key><string>$LOG_DIR/launchd.err</string>
  <key>EnvironmentVariables</key><dict>
    <key>PATH</key><string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
  </dict>
  <key>ThrottleInterval</key><integer>600</integer>
</dict>
</plist>
EOF

# 5) Secrets dans Keychain
echo
echo "===> Saisis le password htpasswd (rest-server) :"
read -rs PWHT
echo "===> Saisis le password du repo restic :"
read -rs PWRE
security delete-generic-password -a lena -s lena-backup-htpasswd 2>/dev/null || true
security delete-generic-password -a lena -s lena-backup-restic   2>/dev/null || true
security add-generic-password -a lena -s lena-backup-htpasswd -w "$PWHT" -U
security add-generic-password -a lena -s lena-backup-restic   -w "$PWRE" -U

# 6) Test connexion
echo
echo "===> Test connexion repo restic"
export RESTIC_REPOSITORY="rest:https://lena:${PWHT}@backup.technotrement.com/lena"
export RESTIC_PASSWORD="$PWRE"
restic snapshots || { echo "Echec connexion. Vérifie creds + Internet."; exit 3; }

# 7) Activation LaunchAgent
launchctl unload "$PLIST" 2>/dev/null || true
launchctl load "$PLIST"
echo
echo "✅ Setup terminé. Premier snapshot va se lancer automatiquement (RunAtLoad)."
echo "Suivi : tail -f $LOG_DIR/lena-backup.log"
