#!/bin/bash

CONFIG_FILE="/etc/network/interfaces"
TEMP_FILE="/tmp/interfaces.new"

echo "⚙️ Configuración de red en Debian"
echo "---------------------------------"

read -p "¿Cuántas interfaces quieres configurar?: " num_ifaces

# Función para nombres de interfaz
get_iface_name() {
    if [ "$1" -eq 1 ]; then
        echo "enp0s3"
    else
        echo "enp0s$((6 + $1))"
    fi
}

# Empezamos archivo temporal
echo "auto lo" > $TEMP_FILE
echo "iface lo inet loopback" >> $TEMP_FILE
echo "" >> $TEMP_FILE

for ((i=1; i<=num_ifaces; i++)); do
    iface=$(get_iface_name $i)

    echo ""
    echo "Configurando interfaz: $iface"

    read -p "¿Usar DHCP? (s/n): " dhcp

    echo "auto $iface" >> $TEMP_FILE

    if [[ "$dhcp" =~ ^[sS]$ ]]; then
        echo "iface $iface inet dhcp" >> $TEMP_FILE

    else
        echo "iface $iface inet static" >> $TEMP_FILE

        read -p "Introduce la IP: " ip
        read -p "Introduce la máscara (ej: 255.255.255.0): " netmask

        echo "    address $ip" >> $TEMP_FILE
        echo "    netmask $netmask" >> $TEMP_FILE

        # DNS
        read -p "¿DNS automático (del servidor) o estático? (auto/estatico): " dns_mode

        if [[ "$dns_mode" == "estatico" ]]; then
            read -p "Introduce DNS: " dns
            echo "    dns-nameservers $dns" >> $TEMP_FILE
        fi

        # Gateway
        read -p "¿Tiene gateway? (s/n): " gw_resp

        if [[ "$gw_resp" =~ ^[sS]$ ]]; then
            read -p "Introduce la gateway: " gateway
            echo "    gateway $gateway" >> $TEMP_FILE
        fi
    fi

    echo "" >> $TEMP_FILE
done

# PREVIEW
echo ""
echo "================ PREVIEW ================"
cat $TEMP_FILE
echo "========================================"
echo ""

read -p "¿Quieres aplicar esta configuración? (s/n): " confirm

if [[ "$confirm" =~ ^[sS]$ ]]; then
    cp $CONFIG_FILE ${CONFIG_FILE}.bak
    cp $TEMP_FILE $CONFIG_FILE
    echo "✅ Configuración aplicada"
    echo "🛟 Backup guardado en ${CONFIG_FILE}.bak"
    echo "🔁 Reinicia con: systemctl restart networking"
else
    echo "❌ Operación cancelada. No se realizaron cambios."
fi

# Limpiar temporal
rm -f $TEMP_FILE