#!/usr/bin/env bash
#
# 🆘 BACKUP & RECOVERY HELPER
# Prepares for disaster recovery and manages backups
#

set -euo pipefail

BACKUP_DIR="${1:-.}/copilot-backup-$(date +%Y%m%d-%H%M%S)"
AGENT_ROOT="/opt/local-agent"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() { echo -e "${BLUE}[$(date +'%H:%M:%S')]${NC} $*"; }
success() { echo -e "${GREEN}✅${NC} $*"; }
warn() { echo -e "${YELLOW}⚠️${NC} $*"; }

# Create backup
create_backup() {
    log "Creating backup..."
    
    mkdir -p "$BACKUP_DIR"
    
    # Bootstrap script
    cp "$AGENT_ROOT/bootstrap.sh" "$BACKUP_DIR/"
    log "  ✓ Bootstrap script"
    
    # Configurations
    mkdir -p "$BACKUP_DIR/config"
    cp -r "$AGENT_ROOT/config/" "$BACKUP_DIR/config/"
    log "  ✓ Configurations"
    
    # Binaries
    mkdir -p "$BACKUP_DIR/bin"
    cp "$AGENT_ROOT/bin"/*.py "$BACKUP_DIR/bin/"
    log "  ✓ Scripts"
    
    # Documentation
    mkdir -p "$BACKUP_DIR/docs"
    cp "$AGENT_ROOT"/*.md "$BACKUP_DIR/docs/" 2>/dev/null || true
    cp "$AGENT_ROOT"/*.txt "$BACKUP_DIR/docs/" 2>/dev/null || true
    log "  ✓ Documentation"
    
    # Store current systemd services
    mkdir -p "$BACKUP_DIR/systemd"
    cp /etc/systemd/system/local-agent*.service "$BACKUP_DIR/systemd/" 2>/dev/null || true
    log "  ✓ Systemd services"
    
    # Create recovery script
    cat > "$BACKUP_DIR/RECOVERY.sh" << 'RECOVERYEOF'
#!/usr/bin/env bash
# Recovery script - run this on new system to restore
set -euo pipefail

BACKUP_DIR="$(cd "$(dirname "$0")" && pwd)"
API_KEY="${1:-}"

if [[ -z "$API_KEY" ]]; then
    echo "Usage: $0 <DEEPSEEK_API_KEY>"
    exit 1
fi

# Run bootstrap with backup API key
bash "$BACKUP_DIR/bootstrap.sh" "$API_KEY"

# Restore custom configs
if [[ -d "$BACKUP_DIR/config" ]]; then
    cp -r "$BACKUP_DIR/config/"* /opt/local-agent/config/
    echo "✓ Custom configurations restored"
fi

# Restore systemd services
if [[ -d "$BACKUP_DIR/systemd" ]]; then
    cp "$BACKUP_DIR/systemd"/*.service /etc/systemd/system/ 2>/dev/null || true
    systemctl daemon-reload
    echo "✓ Systemd services restored"
fi

systemctl restart local-agent-api
echo "✓ Backup recovered successfully!"
RECOVERYEOF
    
    chmod +x "$BACKUP_DIR/RECOVERY.sh"
    log "  ✓ Recovery script"
    
    # Create metadata
    cat > "$BACKUP_DIR/BACKUP_METADATA.txt" << EOF
BACKUP METADATA
═══════════════════════════════════════════
Created: $(date)
System: $(uname -a)
Hostname: $(hostname)
Ubuntu: $(lsb_release -d 2>/dev/null | cut -f2)

Contents:
  ✓ bootstrap.sh - Full setup script
  ✓ config/ - Agent configuration
  ✓ bin/ - API, MCP, DeepSeek scripts
  ✓ docs/ - Documentation
  ✓ systemd/ - Service configurations
  ✓ RECOVERY.sh - Automated recovery

Usage:
  1. Copy this entire directory to secure location
  2. To restore: bash RECOVERY.sh "sk-your-api-key"

⚠️  IMPORTANT: Store API key separately and securely!
    Do not commit it to this backup.
    
    Example:
      gpg --symmetric ~/.deepseek-api-key
      Store in 1Password, Vault, or secure system
EOF
    
    log "  ✓ Metadata file"
    
    success "Backup created: $BACKUP_DIR"
}

# Compress backup
compress_backup() {
    log "Compressing backup..."
    
    local archive="copilot-backup-$(date +%Y%m%d-%H%M%S).tar.gz"
    tar -czf "$archive" -C "$(dirname "$BACKUP_DIR")" "$(basename "$BACKUP_DIR")"
    
    success "Compressed: $archive"
    echo "Size: $(du -sh "$archive" | cut -f1)"
}

# Upload to remote
upload_backup() {
    local remote="${1:-}"
    
    if [[ -z "$remote" ]]; then
        warn "No remote specified (use: backup.sh upload <remote>)"
        return
    fi
    
    log "Uploading backup to $remote..."
    
    scp -r "$BACKUP_DIR" "$remote:~/" || warn "Upload failed"
    success "Uploaded to $remote:$BACKUP_DIR"
}

# Main
cat << 'EOF'
╔════════════════════════════════════════════════════════════════════╗
║                                                                    ║
║         🆘 BACKUP & RECOVERY HELPER                               ║
║                                                                    ║
║    Prepares disaster recovery for Copilot CLI+ environment        ║
║                                                                    ║
╚════════════════════════════════════════════════════════════════════╝

EOF

log "Backup helper started"
create_backup

# Optional: compress
read -p "Compress backup? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    compress_backup
fi

# Optional: upload
read -p "Upload to remote? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    read -p "Remote (user@host): " remote
    upload_backup "$remote"
fi

echo ""
echo "═════════════════════════════════════════════════════════════════"
success "Backup ready!"
echo ""
echo "Next steps:"
echo "  1. Review backup: ls -la $BACKUP_DIR"
echo "  2. Store API key securely (NOT in backup)"
echo "  3. Upload to secure location (git, S3, etc)"
echo "  4. Keep RECOVERY.sh accessible"
echo ""
echo "In case of disaster:"
echo "  bash $BACKUP_DIR/RECOVERY.sh 'sk-your-api-key'"
echo ""
