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

# Restore script for MyRoadTrip backups
# Usage: ./restore-backup.sh [backup-date]

if [[ $EUID -ne 0 ]]; then
  echo "This script must be run as root (use sudo)." >&2
  exit 1
fi

BACKUP_DIR="${BACKUP_DIR:-/srv/myroadtrip/backups}"
BACKUP_DATE="${1:-}"

if [[ -z "$BACKUP_DATE" ]]; then
  echo "Usage: $0 <backup-date>"
  echo ""
  echo "Available backups:"
  ls -lh "$BACKUP_DIR" | grep -E '(redis|logs|Caddyfile|systemd)' | tail -10
  exit 1
fi

echo ">>> Restoring from backup date: $BACKUP_DATE"

# Restore Redis
if [[ -f "$BACKUP_DIR/redis-$BACKUP_DATE.rdb" ]]; then
  echo "Restoring Redis data..."
  systemctl stop redis-server
  cp "$BACKUP_DIR/redis-$BACKUP_DATE.rdb" /var/lib/redis/dump.rdb
  chown redis:redis /var/lib/redis/dump.rdb
  systemctl start redis-server
  echo "✅ Redis restored"
else
  echo "⚠️  No Redis backup found for $BACKUP_DATE"
fi

# Restore Caddy config
if [[ -f "$BACKUP_DIR/Caddyfile-$BACKUP_DATE" ]]; then
  echo "Restoring Caddyfile..."
  cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.before-restore
  cp "$BACKUP_DIR/Caddyfile-$BACKUP_DATE" /etc/caddy/Caddyfile
  systemctl reload caddy
  echo "✅ Caddyfile restored (backup saved to Caddyfile.before-restore)"
else
  echo "⚠️  No Caddyfile backup found for $BACKUP_DATE"
fi

# Restore logs (optional)
if [[ -f "$BACKUP_DIR/logs-$BACKUP_DATE.tar.gz" ]]; then
  read -p "Restore logs? (y/N): " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Restoring logs..."
    tar -xzf "$BACKUP_DIR/logs-$BACKUP_DATE.tar.gz" -C /
    echo "✅ Logs restored"
  fi
fi

echo ""
echo "✅ Restore complete for backup: $BACKUP_DATE"
echo ""
echo "Verify services are running:"
echo "  systemctl status redis-server"
echo "  systemctl status caddy"
echo "  systemctl status myroadtrip-api"
