#!/bin/bash
# Setup backup script and cron job

set -e

echo "Setting up backup system..."

# Create backup directory
mkdir -p /backups/explorer
chown explorer:explorer /backups/explorer

# Create backup script
cat > /usr/local/bin/explorer-backup.sh << 'EOF'
#!/bin/bash
BACKUP_DIR="/backups/explorer"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR

# Backup database
echo "Backing up database..."
pg_dump -U explorer explorer | gzip > $BACKUP_DIR/db_$DATE.sql.gz

# Backup configuration
echo "Backing up configuration..."
tar -czf $BACKUP_DIR/config_$DATE.tar.gz \
    /home/explorer/explorer-monorepo/.env \
    /etc/nginx/sites-available/explorer \
    /etc/systemd/system/explorer-*.service \
    /etc/cloudflared/config.yml 2>/dev/null || true

# Cleanup old backups (keep 30 days)
echo "Cleaning up old backups..."
find $BACKUP_DIR -type f -mtime +30 -delete

echo "Backup completed: $DATE"
EOF

chmod +x /usr/local/bin/explorer-backup.sh
chown explorer:explorer /usr/local/bin/explorer-backup.sh

# Add to crontab (daily at 2 AM)
(crontab -l 2>/dev/null | grep -v explorer-backup.sh; echo "0 2 * * * /usr/local/bin/explorer-backup.sh >> /var/log/explorer-backup.log 2>&1") | crontab -

echo "Backup system configured!"
echo "Backups will run daily at 2 AM"
echo "Backup location: /backups/explorer"
echo ""
echo "To run backup manually: /usr/local/bin/explorer-backup.sh"

