#!/bin/bash

# Server Backup Script
# Creates comprehensive backup of all applications and system state

set -e

# Create timestamped backup directory
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/home/jcbeasley/backups/$TIMESTAMP"
LOG_FILE="$BACKUP_DIR/backup.log"

echo "Starting server backup at $(date)" | tee $LOG_FILE

# Create backup directory
mkdir -p $BACKUP_DIR
echo "Created backup directory: $BACKUP_DIR" | tee -a $LOG_FILE

# Backup entire home directory
echo "Backing up home directory..." | tee -a $LOG_FILE
tar -czf $BACKUP_DIR/home_backup.tar.gz -C / --exclude='home/jcbeasley/backups' --exclude='home/jcbeasley/.cache' home/jcbeasley 2>>$LOG_FILE
echo "Home directory backup completed" | tee -a $LOG_FILE

# Backup running processes information
echo "Documenting running processes..." | tee -a $LOG_FILE
ps aux > $BACKUP_DIR/running_processes.txt
ss -tulpn > $BACKUP_DIR/port_usage.txt
crontab -l > $BACKUP_DIR/crontab_backup.txt 2>/dev/null || echo "No crontab" > $BACKUP_DIR/crontab_backup.txt

# Backup each application individually
echo "Backing up individual applications..." | tee -a $LOG_FILE

# IT Site Survey AI (Port 3003)
if [ -d "/home/jcbeasley/.openclaw/workspace/Projects/site-survey-ai" ]; then
    tar -czf $BACKUP_DIR/site-survey-ai_backup.tar.gz -C /home/jcbeasley/.openclaw/workspace/Projects site-survey-ai 2>>$LOG_FILE
    echo "IT Site Survey AI backup completed" | tee -a $LOG_FILE
    
    # Export current data if application is running
    if curl -s http://localhost:3003/health > /dev/null 2>&1; then
        echo "Exporting IT Site Survey AI data..." | tee -a $LOG_FILE
        curl -s http://localhost:3003/api/surveys/responses > $BACKUP_DIR/site_survey_data.json 2>>$LOG_FILE
        echo "IT Site Survey AI data export completed" | tee -a $LOG_FILE
    fi
fi

# Client Onboarding (Port 5000)
if [ -d "/home/jcbeasley/.openclaw/workspace/Projects/client-onboarding" ]; then
    tar -czf $BACKUP_DIR/client-onboarding_backup.tar.gz -C /home/jcbeasley/.openclaw/workspace/Projects client-onboarding 2>>$LOG_FILE
    echo "Client Onboarding backup completed" | tee -a $LOG_FILE
fi

# Projects Manager (Port 3456)
if [ -d "/home/jcbeasley/projects-manager" ]; then
    tar -czf $BACKUP_DIR/projects-manager_backup.tar.gz -C /home/jcbeasley projects-manager 2>>$LOG_FILE
    echo "Projects Manager backup completed" | tee -a $LOG_FILE
fi

# Document process configurations
echo "Documenting process configurations..." | tee -a $LOG_FILE
echo "# Process Start Commands - Backup $TIMESTAMP" > $BACKUP_DIR/process_configs.txt
echo "IT Site Survey AI: cd /home/jcbeasley/.openclaw/workspace/Projects/site-survey-ai && source venv/bin/activate && nohup python3 app.py > app.log 2>&1 &" >> $BACKUP_DIR/process_configs.txt
echo "Client Onboarding: cd /home/jcbeasley/.openclaw/workspace/Projects/client-onboarding && source venv/bin/activate && nohup python3 app.py > app.log 2>&1 &" >> $BACKUP_DIR/process_configs.txt
echo "Projects Manager: cd /home/jcbeasley/projects-manager && source venv/bin/activate && nohup python3 app.py > app.log 2>&1 &" >> $BACKUP_DIR/process_configs.txt

# Verify backups
echo "Verifying backups..." | tee -a $LOG_FILE
if [ -f "$BACKUP_DIR/home_backup.tar.gz" ]; then
    BACKUP_SIZE=$(du -h $BACKUP_DIR/home_backup.tar.gz | cut -f1)
    echo "Home backup size: $BACKUP_SIZE" | tee -a $LOG_FILE
fi

# Create restore script
echo "Creating restore script..." | tee -a $LOG_FILE
cat > $BACKUP_DIR/restore.sh << 'EOF'
#!/bin/bash

# Restore Script for Backup TIMESTAMP
# Usage: ./restore.sh [application_name]

BACKUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TIMESTAMP="$(basename $BACKUP_DIR)"

echo "Starting restore from backup $TIMESTAMP"

if [ "$1" == "" ]; then
    echo "Restoring entire server..."
    # Stop all python applications
    pkill -f "python.*app.py" 2>/dev/null || true
    pkill -f "python.*server.py" 2>/dev/null || true
    
    # Restore home directory
    tar -xzf $BACKUP_DIR/home_backup.tar.gz -C /
    
    echo "Server restore completed. Please restart applications manually."
elif [ "$1" == "site-survey-ai" ]; then
    echo "Restoring IT Site Survey AI..."
    pkill -f "site-survey-ai" 2>/dev/null || true
    tar -xzf $BACKUP_DIR/site-survey-ai_backup.tar.gz -C /home/jcbeasley/.openclaw/workspace/Projects/
    echo "IT Site Survey AI restore completed."
elif [ "$1" == "client-onboarding" ]; then
    echo "Restoring Client Onboarding..."
    pkill -f "client-onboarding" 2>/dev/null || true
    tar -xzf $BACKUP_DIR/client-onboarding_backup.tar.gz -C /home/jcbeasley/.openclaw/workspace/Projects/
    echo "Client Onboarding restore completed."
elif [ "$1" == "projects-manager" ]; then
    echo "Restoring Projects Manager..."
    pkill -f "projects-manager" 2>/dev/null || true
    tar -xzf $BACKUP_DIR/projects-manager_backup.tar.gz -C /home/jcbeasley/
    echo "Projects Manager restore completed."
else
    echo "Unknown application: $1"
    echo "Available applications: site-survey-ai, client-onboarding, projects-manager"
    exit 1
fi
EOF

# Make restore script executable
chmod +x $BACKUP_DIR/restore.sh

# Update timestamp in restore script
sed -i "s/TIMESTAMP/$TIMESTAMP/g" $BACKUP_DIR/restore.sh

echo "Backup completed successfully at $(date)" | tee -a $LOG_FILE
echo "Backup location: $BACKUP_DIR" | tee -a $LOG_FILE
echo "To restore: cd $BACKUP_DIR && ./restore.sh" | tee -a $LOG_FILE