#!/bin/bash
# Restore Script - Restores backups from cloud storage

set -e

REMOTE_NAME="${1:-remix-backup}"
REMOTE_BACKUP_DIR="${2:-remix-sniper-backup}"
LOCAL_RESTORE_DIR="$HOME/.clawdbot/workspace/restore-from-cloud-$(date +%Y%m%d-%H%M%S)"

if [[ -z "$1" ]]; then
  echo "ERROR: Please specify remote name"
  echo "Usage: $0 <remote-name> [backup-directory] [backup-subdir]"
  echo ""
  echo "Examples:"
  echo "  $0 gdrive remix-sniper-backup backup-cloud-20260119-120000"
  echo "  $0 s3 backup"
  echo ""
  echo "To list available backups:"
  echo "  rclone ls <remote-name>:<backup-directory>/"
  echo ""
  echo "See: https://rclone.org/ for full setup instructions"
  exit 1
fi

echo "=========================================="
echo "CLOUD RESTORE SCRIPT"
echo "=========================================="
echo "Remote: $REMOTE_NAME"
echo "Source: $REMOTE_BACKUP_DIR/${3:-latest}/"
echo "Destination: $LOCAL_RESTORE_DIR"
echo ""

# Check if remote exists
if ! rclone listremotes 2>/dev/null | grep -q "^$REMOTE_NAME:"; then
  echo "ERROR: Remote '$REMOTE_NAME:' not configured"
  exit 1
fi

# List available backups if no specific backup is specified
if [[ -z "$3" ]]; then
  echo "Available backups:"
  echo ""
  rclone lsd "$REMOTE_NAME:$REMOTE_BACKUP_DIR/" 2>/dev/null || echo "No backups found"
  echo ""
  echo "Usage: $0 $REMOTE_NAME $REMOTE_BACKUP_DIR <backup-name>"
  exit 0
fi

# Download backup
echo "[1/2] Downloading backup from cloud..."
mkdir -p "$LOCAL_RESTORE_DIR"

rclone sync "$REMOTE_NAME:$REMOTE_BACKUP_DIR/$3/" "$LOCAL_RESTORE_DIR/" \
  --progress \
  --transfers 4

echo ""
echo "   ✓ Downloaded backup"
echo ""

# Restore from local copy
echo "[2/2] Restoring from local backup..."
echo ""

# Verify checksums
if [[ -f "$LOCAL_RESTORE_DIR/sha256-checksums.txt" ]]; then
  echo "Verifying backup integrity..."
  cd "$LOCAL_RESTORE_DIR"
  shasum -c sha256-checksums.txt 2>/dev/null
  if [[ $? -eq 0 ]]; then
    echo "   ✓ All files verified"
  else
    echo "   ⚠️  Checksum mismatch - some files may be corrupted"
    read -p "Continue anyway? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
      exit 1
    fi
  fi
else
  echo "   ⚠️  Checksums not found, skipping verification"
fi
echo ""

# Restore crontab
echo "[1/7] Restoring crontab..."
if [[ -f "$LOCAL_RESTORE_DIR/crontab-backup.txt" ]]; then
  crontab "$LOCAL_RESTORE_DIR/crontab-backup.txt"
  echo "   ✓ Restored $(wc -l < "$LOCAL_RESTORE_DIR/crontab-backup.txt") cron jobs"
else
  echo "   ⚠️  crontab-backup.txt not found, skipping"
fi

# Restore launchd services
echo "[2/7] Restoring launchd services..."
if [[ -d "$LOCAL_RESTORE_DIR/launchd" ]]; then
  mkdir -p ~/Library/LaunchAgents/
  cp -R "$LOCAL_RESTORE_DIR/launchd/"* ~/Library/LaunchAgents/ 2>/dev/null

  if [[ -f ~/Library/LaunchAgents/com.jakeshore.remix-sniper.plist ]]; then
    launchctl load -w ~/Library/LaunchAgents/com.jakeshore.remix-sniper.plist 2>/dev/null
    echo "   ✓ Loaded remix-sniper launchd service"
  fi
else
  echo "   ⚠️  launchd directory not found, skipping"
fi

# Restore PostgreSQL database
echo "[3/7] Restoring PostgreSQL database..."
if [[ -f "$LOCAL_RESTORE_DIR/remix_sniper-db.sql" ]]; then
  if command -v /opt/homebrew/opt/postgresql@16/bin/psql &> /dev/null; then
    /opt/homebrew/opt/postgresql@16/bin/psql -d remix_sniper < "$LOCAL_RESTORE_DIR/remix_sniper-db.sql" 2>/dev/null
    echo "   ✓ Restored database ($(wc -l < "$LOCAL_RESTORE_DIR/remix_sniper-db.sql") lines)"
  else
    echo "   ⚠️  PostgreSQL not installed - install first then run:"
    echo "      /opt/homebrew/opt/postgresql@16/bin/psql -d remix_sniper < \"$LOCAL_RESTORE_DIR/remix_sniper-db.sql\""
  fi
else
  echo "   ⚠️  Database dump not found, skipping"
fi

# Restore Remix Sniper tracking data
echo "[4/7] Restoring Remix Sniper tracking data..."
if [[ -d "$LOCAL_RESTORE_DIR/remix-sniper" ]]; then
  mkdir -p ~/.remix-sniper
  cp -R "$LOCAL_RESTORE_DIR/remix-sniper/"* ~/.remix-sniper/ 2>/dev/null
  echo "   ✓ Restored tracking data ($(find ~/.remix-sniper -type f | wc -l) files)"
else
  echo "   ⚠️  Remix Sniper data not found, skipping"
fi

# Restore environment files
echo "[5/7] Restoring environment files..."
if [[ -d "$LOCAL_RESTORE_DIR/env-files" ]]; then
  mkdir -p ~/projects/remix-sniper/
  cp "$LOCAL_RESTORE_DIR/env-files/.env" ~/projects/remix-sniper/ 2>/dev/null
  echo "   ✓ Restored .env file"
else
  echo "   ⚠️  Environment files not found, skipping"
fi

# Restore Clawdbot workspace
echo "[6/7] Restoring Clawdbot workspace..."
if [[ -d "$LOCAL_RESTORE_DIR/clawdbot-workspace" ]]; then
  mkdir -p ~/.clawdbot/workspace/
  cp -R "$LOCAL_RESTORE_DIR/clawdbot-workspace/"* ~/.clawdbot/workspace/ 2>/dev/null
  echo "   ✓ Restored workspace ($(find ~/.clawdbot/workspace -type f | wc -l) files)"
else
  echo "   ⚠️  Workspace backup not found, skipping"
fi

# Restore scripts
echo "[7/7] Restoring custom scripts..."
if [[ -d "$LOCAL_RESTORE_DIR/scripts" ]]; then
  mkdir -p ~/.clawdbot/workspace/
  cp "$LOCAL_RESTORE_DIR/scripts/"* ~/.clawdbot/workspace/ 2>/dev/null
  chmod +x ~/.clawdbot/workspace/*.sh 2>/dev/null
  echo "   ✓ Restored custom scripts"
else
  echo "   ⚠️  Scripts directory not found, skipping"
fi

echo ""
echo "=========================================="
echo "RESTORE COMPLETE"
echo "=========================================="
echo ""
echo "Local restore location: $LOCAL_RESTORE_DIR"
echo ""
echo "Next steps:"
echo "  1. Verify crontab: crontab -l"
echo "  2. Check launchd services: launchctl list | grep remix-sniper"
echo "  3. Check PostgreSQL: /opt/homebrew/opt/postgresql@16/bin/psql -d remix_sniper -c '\l'"
echo "  4. Test Remix Sniper bot: Check if bot is online in Discord"
echo ""
echo "Note: You may need to:"
echo "  - Restart PostgreSQL: brew services restart postgresql@16"
echo "  - Restart launchd services: launchctl restart com.jakeshore.remix-sniper"
echo ""
