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

# Backup script for MyRoadTrip
# Usage: ./backup.sh [retention-days]

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}"
RETENTION_DAYS="${1:-7}"
DATE=$(date +%Y%m%d-%H%M%S)

mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"

echo ">>> Starting backup: $DATE"

# 1. Redis Backup
if [[ -f /var/lib/redis/dump.rdb ]]; then
  echo "Backing up Redis..."
  # Trigger a save if redis is running
  if systemctl is-active --quiet redis-server; then
    redis-cli save >/dev/null 2>&1 || true
  fi
  cp /var/lib/redis/dump.rdb "$BACKUP_DIR/redis-$DATE.rdb"
else
  echo "⚠️  Redis dump not found at /var/lib/redis/dump.rdb"
fi

# 2. Config Backup
echo "Backing up configurations..."
if [[ -f /etc/caddy/Caddyfile ]]; then
  cp /etc/caddy/Caddyfile "$BACKUP_DIR/Caddyfile-$DATE"
fi

# 3. Env Backup
if [[ -d /srv/myroadtrip ]]; then
  tar -czf "$BACKUP_DIR/envs-$DATE.tar.gz" -C /srv/myroadtrip .env.production repo/apps/api/.env.production repo/apps/web/.env.production 2>/dev/null || true
fi

# 4. Cleanup old backups
echo "Cleaning up backups older than $RETENTION_DAYS days..."
find "$BACKUP_DIR" -type f -mtime +$RETENTION_DAYS -delete

echo "✅ Backup complete: $DATE"
echo "Saved to: $BACKUP_DIR"
