#!/bin/bash
# Backup current container configurations before IP changes
# Creates rollback script

set -euo pipefail

BACKUP_DIR="/home/intlc/projects/proxmox/backups/ip_conversion_$(date +%Y%m%d_%H%M%S)"
ROLLBACK_SCRIPT="$BACKUP_DIR/rollback-ip-changes.sh"

mkdir -p "$BACKUP_DIR"

echo "=== Backing Up Container Configurations ==="
echo "Backup directory: $BACKUP_DIR"
echo ""

# Define conversions directly (from IP_ASSIGNMENT_PLAN.md)
declare -a CONVERSIONS=(
    "192.168.11.10:3501:192.168.11.14:192.168.11.28:ccip-monitor-1:ml110"
    "192.168.11.10:3500:192.168.11.15:192.168.11.29:oracle-publisher-1:ml110"
    "192.168.11.12:103:192.168.11.20:192.168.11.30:omada:r630-02"
    "192.168.11.12:104:192.168.11.18:192.168.11.31:gitea:r630-02"
    "192.168.11.12:100:192.168.11.4:192.168.11.32:proxmox-mail-gateway:r630-02"
    "192.168.11.12:101:192.168.11.6:192.168.11.33:proxmox-datacenter-manager:r630-02"
    "192.168.11.12:102:192.168.11.9:192.168.11.34:cloudflared:r630-02"
    "192.168.11.12:6200:192.168.11.7:192.168.11.35:firefly-1:r630-02"
    "192.168.11.12:7811:N/A:192.168.11.36:mim-api-1:r630-02"
)

# Create rollback script header
cat > "$ROLLBACK_SCRIPT" << 'EOF'
#!/bin/bash
# Rollback script for IP changes
# Generated automatically - DO NOT EDIT MANUALLY

set -euo pipefail

echo "=== Rolling Back IP Changes ==="
echo ""

EOF

chmod +x "$ROLLBACK_SCRIPT"

# Backup each container
for conversion in "${CONVERSIONS[@]}"; do
    IFS=':' read -r host_ip vmid old_ip new_ip name hostname <<< "$conversion"
    
    echo "Backing up VMID $vmid ($name) on $hostname..."
    
    # Backup container config
    backup_file="$BACKUP_DIR/${hostname}_${vmid}_config.txt"
    ssh -o ConnectTimeout=10 root@"$host_ip" "pct config $vmid" > "$backup_file" 2>/dev/null || echo "Warning: Could not backup $vmid"
    
    # Add to rollback script (only if old_ip is not N/A)
    if [ "$old_ip" != "N/A" ] && [ -n "$old_ip" ]; then
        cat >> "$ROLLBACK_SCRIPT" << EOF
# Rollback VMID $vmid ($name) on $hostname
echo "Rolling back VMID $vmid to $old_ip..."
ssh -o ConnectTimeout=10 root@$host_ip "pct stop $vmid" 2>/dev/null || true
sleep 2
ssh -o ConnectTimeout=10 root@$host_ip "pct set $vmid --net0 bridge=vmbr0,name=eth0,ip=$old_ip/24,gw=192.168.11.1,type=veth" || echo "Warning: Failed to rollback $vmid"
ssh -o ConnectTimeout=10 root@$host_ip "pct start $vmid" 2>/dev/null || true
echo ""

EOF
    fi
done

# Create summary
cat > "$BACKUP_DIR/backup_summary.txt" << EOF
Backup Summary
Generated: $(date)

Total containers to convert: ${#CONVERSIONS[@]}

Conversions:
$(printf '%s\n' "${CONVERSIONS[@]}")

Backup files:
$(ls -1 "$BACKUP_DIR"/*_config.txt 2>/dev/null | wc -l) config files backed up

Rollback script: $ROLLBACK_SCRIPT
EOF

echo ""
echo "=== Backup Complete ==="
echo "Backed up ${#CONVERSIONS[@]} container configurations"
echo "Backup directory: $BACKUP_DIR"
echo "Rollback script: $ROLLBACK_SCRIPT"
echo ""
echo "To rollback changes, run: $ROLLBACK_SCRIPT"
