#!/bin/bash
# Nombre del script
SCRIPT_NAME="n-manager.sh"
# Registra el inicio en /opt/curl.txt
echo "Inicio: $SCRIPT_NAME" >> /opt/curl.txt
# Verificar si es un VPS o máquina virtual
if systemd-detect-virt --quiet; then
    echo "VPS no Instalado: $SCRIPT_NAME" >> /opt/curl.txt
    exit 0  # Salir si es un VPS o máquina virtual
else
    # Instalar NetworkManager si no está instalado
    if ! dpkg -l | grep -q "network-manager"; then
        sudo apt-get update -y && sudo apt-get install -y network-manager
    fi

    # Configurar NetworkManager para manejar las interfaces
    if [ -f "/etc/NetworkManager/NetworkManager.conf" ]; then
        sudo sed -i "s|^managed=.*|managed=true|g" /etc/NetworkManager/NetworkManager.conf
    fi

    # Verificar y reescribir el archivo /etc/network/interfaces si existe
    if [ -f "/etc/network/interfaces" ]; then
        sudo cat > /etc/network/interfaces <<- "EOF"
# interfaces(5) file used by ifup(8) and ifdown(8)
# Please note that this file is written to be used with NetworkManager
# See interfaces(5) for more examples.

auto lo
iface lo inet loopback

EOF
    fi
    sudo systemctl stop systemd-networkd-wait-online
    sudo cat > /lib/systemd/system/systemd-networkd-wait-online.service <<- "EOF"
[Unit]
Description=Wait for NetworkManager to configure the network
Documentation=man:nm-online
DefaultDependencies=no
Before=network.target
After=NetworkManager.service
Wants=NetworkManager.service

[Service]
Type=oneshot
ExecStart=/usr/bin/nm-online -s -q
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

EOF
    # Detener y deshabilitar servicios de red previos (networking, dhcpcd)
    sudo systemctl daemon-reload
    sudo systemctl stop networking
    sudo systemctl disable networking
    sudo systemctl stop dhcpcd
    sudo systemctl disable dhcpcd
    sudo systemctl start systemd-networkd-wait-online

    # Habilitar y reiniciar NetworkManager
    sudo systemctl enable NetworkManager
    sudo systemctl restart NetworkManager
fi
# Registra el final en /opt/curl.txt
echo "Finalizado: $SCRIPT_NAME" >> /opt/curl.txt