#!/bin/bash
set -e


. /usr/share/debconf/confmodule

KEA_CTRL_AGENT_CONF="/etc/kea/kea-ctrl-agent.conf"
db_get opengnsys/ogdhcp_interfaces
OGDHCP_INTERFACES="$RET"
db_get opengnsys/ogdhcp_ip
OGDHCP_IP="$RET"
db_get opengnsys/ogdhcp_ogbootIP
OGBOOT_IP="$RET"

case "$1" in
    configure)
        echo "Configurando ogdhcp..."
        
        # Configuración de kea-ctrl-agent
        echo "Eliminando autenticación de kea-ctrl-agent..."
        if [ -e "$KEA_CTRL_AGENT_CONF" ]; then
            dpkg-divert --package ogdhcp --divert "$KEA_CTRL_AGENT_CONF.dpkg-dist" --rename "$KEA_CTRL_AGENT_CONF"
            cp -a "$KEA_CTRL_AGENT_CONF.dpkg-dist" "$KEA_CTRL_AGENT_CONF"
            if grep -q '^[^#]*"authentication": {' "$KEA_CTRL_AGENT_CONF"; then
                sed -i '/"authentication": {/,/^[[:space:]]*},/ {
                s/^\([[:space:]]*\)\([^#]\)/\1#\2/
                }' "$KEA_CTRL_AGENT_CONF"
            fi
        fi

        # Configuración de AppArmor
        APPARMOR_LOCAL_PROFILE="/etc/apparmor.d/local/usr.sbin.kea-dhcp4"
        echo "Añadiendo permisos personalizados a AppArmor para kea-dhcp4..."
        mkdir -p "$(dirname "$APPARMOR_LOCAL_PROFILE")"
        cat > "$APPARMOR_LOCAL_PROFILE" <<EOF
/etc/kea/ rw,
/etc/kea/** rw,
EOF

        echo "Recargando perfiles de AppArmor..."
        apparmor_parser -r /etc/apparmor.d/usr.sbin.kea-dhcp4
        if [ $? -eq 0 ]; then
            echo "El perfil de AppArmor se recargó correctamente."
        else
            echo "Error al recargar el perfil de AppArmor."
        fi

        # Configuración de nginx
        echo "Configurando nginx..."
        PHP_VERSION=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')
        if [ ! -f /etc/nginx/sites-available/ogdhcp.conf ]; then
            cp /opt/opengnsys/ogdhcp/etc/nginxServer.conf.tmpl /etc/nginx/sites-available/ogdhcp.conf
            sed -i "s|__PHPVERSION__|$PHP_VERSION|g" /etc/nginx/sites-available/ogdhcp.conf
            sed -i "s|__SERVERIP__|$OGDHCP_IP|g" /etc/nginx/sites-available/ogdhcp.conf
            sed -i "s|__PUBLICDIR__|/opt/opengnsys/ogdhcp/public|g" /etc/nginx/sites-available/ogdhcp.conf
            ln -s /etc/nginx/sites-available/ogdhcp.conf /etc/nginx/sites-enabled/ogdhcp.conf
        else
            echo "El archivo /etc/nginx/sites-available/ogdhcp.conf ya existe."
        fi

        # Configuración de php-fpm
        echo "Configurando php-fpm..."
        if [ ! -f /etc/php/$PHP_VERSION/fpm/pool.d/ogdhcp.conf ]; then
            cp /opt/opengnsys/ogdhcp/etc/php/fpm/ogdhcp-fpm.conf /etc/php/$PHP_VERSION/fpm/pool.d/ogdhcp.conf
        fi

        # Configuración de kea-dhcp4
        echo "Configurando kea-dhcp4..."
        IFS=',' read -r -a INTERFACES <<< "$OGDHCP_INTERFACES"
        KEA_CONFIG="/etc/kea/kea-dhcp4.conf"
        if [ -e "$KEA_CONFIG" ]; then
            dpkg-divert --package ogdhcp --divert "$KEA_CONFIG.dpkg-dist" --rename "$KEA_CONFIG"
            cat > "$KEA_CONFIG" <<EOF
{
    "Dhcp4": {
        "interfaces-config": {
            "interfaces": [ $( 
                for interface in "${INTERFACES[@]}"; do
                    echo "\"$interface\""
                done | paste -sd "," -
            ) ]
        },
        "client-classes": [
            {
                "name": "UEFI-64",
                "test": "not substring(option[60].hex,0,20) == 'PXEClient:Arch:00000'",
                "boot-file-name": "ipxe.efi",
                "next-server": "$OGBOOT_IP"
            },
            {
                "name": "Legacy",
                "test": "substring(option[60].hex,0,20) == 'PXEClient:Arch:00000'",
                "boot-file-name": "undionly.kpxe",
                "next-server": "$OGBOOT_IP"
            }
        ],
        "control-socket": {
            "socket-name": "/run/kea/kea4-ctrl-socket",
            "socket-type": "unix"
        }
    }
}
EOF
        fi
    ;;
    
    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument '$1'" >&2
        exit 1
    ;;
esac


chown opengnsys:www-data /opt/opengnsys/
chown -R opengnsys:www-data /opt/opengnsys/ogdhcp
chown -R _kea:_kea /etc/kea

# Reiniciar servicios
systemctl daemon-reload
systemctl restart nginx
systemctl restart kea-dhcp4-server
systemctl restart kea-ctrl-agent
systemctl restart php$PHP_VERSION-fpm

exit 0
