#!/bin/bash

# Setup automated backups for Stoatchat
# This script configures a daily backup at 2 AM

set -e

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log() {
    echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

success() {
    echo -e "${GREEN}✅ $1${NC}"
}

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
fi

STOATCHAT_DIR="/root/stoatchat"
BACKUP_SCRIPT="${STOATCHAT_DIR}/backup.sh"

# Check if backup script exists
if [ ! -f "$BACKUP_SCRIPT" ]; then
    echo "❌ Backup script not found at $BACKUP_SCRIPT"
    exit 1
fi

log "Setting up automated daily backups for Stoatchat..."

# Create cron job for daily backup at 2 AM
CRON_JOB="0 2 * * * $BACKUP_SCRIPT >> /var/log/stoatchat-backup.log 2>&1"

# Check if cron job already exists
if crontab -l 2>/dev/null | grep -q "$BACKUP_SCRIPT"; then
    log "Backup cron job already exists, updating..."
    # Remove existing job and add new one
    (crontab -l 2>/dev/null | grep -v "$BACKUP_SCRIPT"; echo "$CRON_JOB") | crontab -
else
    log "Adding new backup cron job..."
    # Add new cron job
    (crontab -l 2>/dev/null; echo "$CRON_JOB") | crontab -
fi

success "Daily backup scheduled for 2:00 AM"

# Create log rotation for backup logs
log "Setting up log rotation..."
cat > /etc/logrotate.d/stoatchat-backup << EOF
/var/log/stoatchat-backup.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 644 root root
}
EOF

success "Log rotation configured"

# Create backup monitoring script
log "Creating backup monitoring script..."
cat > "${STOATCHAT_DIR}/check-backup-health.sh" << 'EOF'
#!/bin/bash

# Check backup health and send alerts if needed

BACKUP_DIR="/root/stoatchat-backups"
ALERT_EMAIL="admin@example.com"  # Change this to your email
MAX_AGE_HOURS=26  # Alert if no backup in last 26 hours

# Find the most recent backup
LATEST_BACKUP=$(find "$BACKUP_DIR" -name "stoatchat_backup_*.tar.gz" -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -d' ' -f2-)

if [ -z "$LATEST_BACKUP" ]; then
    echo "❌ No backups found in $BACKUP_DIR"
    exit 1
fi

# Check age of latest backup
BACKUP_AGE=$(find "$LATEST_BACKUP" -mtime +1 | wc -l)

if [ "$BACKUP_AGE" -gt 0 ]; then
    echo "⚠️  Latest backup is older than 24 hours: $LATEST_BACKUP"
    echo "Backup age: $(stat -c %y "$LATEST_BACKUP")"
    exit 1
else
    echo "✅ Backup is current: $LATEST_BACKUP"
    echo "Backup size: $(du -h "$LATEST_BACKUP" | cut -f1)"
    echo "Backup date: $(stat -c %y "$LATEST_BACKUP")"
fi

# Check backup integrity
if tar -tzf "$LATEST_BACKUP" >/dev/null 2>&1; then
    echo "✅ Backup integrity verified"
else
    echo "❌ Backup integrity check failed!"
    exit 1
fi

# Check disk space
DISK_USAGE=$(df "$BACKUP_DIR" | tail -1 | awk '{print $5}' | sed 's/%//')
if [ "$DISK_USAGE" -gt 80 ]; then
    echo "⚠️  Disk usage is high: ${DISK_USAGE}%"
    echo "Consider cleaning old backups or expanding storage"
fi

echo "✅ Backup health check completed successfully"
EOF

chmod +x "${STOATCHAT_DIR}/check-backup-health.sh"
success "Backup monitoring script created"

# Add weekly backup health check
HEALTH_CRON_JOB="0 8 * * 1 ${STOATCHAT_DIR}/check-backup-health.sh >> /var/log/stoatchat-backup-health.log 2>&1"
if ! crontab -l 2>/dev/null | grep -q "check-backup-health.sh"; then
    (crontab -l 2>/dev/null; echo "$HEALTH_CRON_JOB") | crontab -
    success "Weekly backup health check scheduled for Mondays at 8:00 AM"
fi

# Show current cron jobs
log "Current backup-related cron jobs:"
crontab -l | grep -E "(backup|stoatchat)" || echo "No backup cron jobs found"

echo
echo "=================================================="
echo -e "${GREEN}🎉 AUTOMATED BACKUP SETUP COMPLETE! 🎉${NC}"
echo "=================================================="
echo "✅ Daily backup scheduled for 2:00 AM"
echo "✅ Weekly health check scheduled for Mondays at 8:00 AM"
echo "✅ Log rotation configured"
echo "✅ Backup monitoring script created"
echo
echo "Backup locations:"
echo "  📁 Backups: /root/stoatchat-backups/"
echo "  📄 Logs: /var/log/stoatchat-backup.log"
echo "  📄 Health logs: /var/log/stoatchat-backup-health.log"
echo
echo "Manual commands:"
echo "  🔧 Run backup now: $BACKUP_SCRIPT"
echo "  🔍 Check backup health: ${STOATCHAT_DIR}/check-backup-health.sh"
echo "  📋 View cron jobs: crontab -l"
echo "  📄 View backup logs: tail -f /var/log/stoatchat-backup.log"
echo
echo "Setup completed at: $(date)"
echo "=================================================="
