#!/bin/bash

. /etc/default/vx-dga-variables/vx-dga-variables-general.conf

modificar_ip_cache(){
    unset IPCACHE
    # modificar_ip_cache old_IP new_IP
    [[ "$1" = "$2" ]] && return 0
    # Modificamos la IP del Caché en el documento de variables:
    FILEVAR="/etc/default/vx-dga-variables/vx-dga-variables-general.conf"
    
    # Como vamos a modificar la ip del caché, debemos reiniciar el servicio de carpetas compartidos si está lanzado
    /sbin/start-stop-daemon --status --name nfs-cliente.sh && /sbin/start-stop-daemon --oknodo --stop --name nfs-cliente.sh --retry=TERM/5/KILL/2
    if [[ -f "$FILEVAR" ]]; then
        
        if sed -i "s#^IPCACHE=.*#IPCACHE=${2}#g" "$FILEVAR" ; then
            export IPCACHE="${2}"
        fi
    fi
    /sbin/start-stop-daemon --start --quiet -m --name nfs-cliente.sh --pidfile /run/nfs-cliente.pid -b -a /usr/bin/nfs-cliente.sh
    
    # Modificamos la configuración del proxy apt
    local proxy_file="/etc/apt/apt.conf.d/01cache_proxy"
    #Comprobamos lo primero si el servidor caché está en la red
    if ping -c 1 "${2}" > /dev/null 2>&1 && nc -zv "${2}" 3142 > /dev/null 2>&1 ; then
        # Servidor Cache que ofrece servicio APT-CACHER"
        echo "Acquire::http { Proxy \"http://${2}:3142\"; };" > $proxy_file
        echo 'Acquire::https { Proxy "false"; };' >> $proxy_file
    else
        # Borrar el posible archivo generado anteriormente del proxy-cache
        [[ -f $proxy_file ]] && rm -f $proxy_file
    fi
}
OLDCACHE="$IPCACHE"

modificar_ip_cache "${OLDCACHE}" "192.168.0.249"