#!/bin/bash
# CTparental
#
# par Guillaume MARSAT
# Corrections orthographiques par Pierre-Edouard TESSIER
# une partie du code est tirée du script alcasar-bl.sh créé par Franck BOUIJOUX et Richard REY
# présente dans le code du projet alcasar en version 2.6.1 ; web page http://www.alcasar.net/

# This script is distributed under the Gnu General Public License (GPL)
DIR_CONF="/etc/CTparental"
DIR_SHARE="/usr/share/CTparental"
FILE_CONF="$DIR_CONF/CTparental.conf"
if [ -f "$DIR_CONF/CTparental.conf" ];then
    if [ "$( grep -c "^LANG=" $FILE_CONF )" -ge 1 ] ;then
        LANG="$( grep "^LANG" $FILE_CONF | cut -d "=" -f2 )"
        export LANG
    fi
fi
DIRLOCALE=${DIRLOCALE:="/usr/share/locale"}
#chargement des locales.
set -a
source /usr/bin/gettext.sh
set +a
export TEXTDOMAINDIR="$DIRLOCALE"
export TEXTDOMAIN="ctparental"
CHEMINCTPARENTLE="$(readlink -f "$0")"


## imports du plugin de la distribution si il existe
if [ -f "${DIR_CONF}/dist.conf" ];then 
source "${DIR_CONF}/dist.conf"
fi

#### UID MINIMUM pour les UTILISATEURS
UIDMINUSER=${UIDMINUSER:=1000}
UIDGUEST=${UIDGUEST:=998}
# considère comme root tous les utilisateurs avec un uid inférieur ou
# égal à 499,ce qui permet à apt-get,urpmi,yum... de lancer le script
# sans erreur.
if [ ! $UID -lt $UIDMINUSER ]; then
    gettext 'Root rights needed to run this script.'
    echo ""
    exit 1
fi
## On ne fait rien si ctparental est déja en cours de traitement long.
PIDFILE="/var/run/CTparental.pid"
PIDFILEWAIT="/var/run/CTparentalwait.pid"
if [ -f $PIDFILE ];then
    pidtest=$(cat $PIDFILE)
    if [ "$( ps -A | grep -c "$pidtest")" -eq 0 ] ; then
        rm -f $PIDFILE
    else
        ## si déja 2 processus sont lancer on ferme le nouveaux.
        if [ -f $PIDFILEWAIT ] ; then
            gettext 'Too many processes already in progress, please try again later.'
            echo ""
            exit 2
        fi
        echo $$ > $PIDFILEWAIT
        ## on attend que le processus déja en cour ce termine max 55 secondes
        eval_gettext "Waiting for the end of the process \$pidtest"
        for ((count=0 ; 55 - count ; count++))
        do
            sleep 1
            echo -n "."
            if [ "$( ps -A | grep -c "$pidtest")" -eq 0 ] ; then
                rm -f $PIDFILE
                break
            fi
        done
        echo ""
        ## si le processus et encore en cour au bout de 55 seconde on abendonne l'éxecution d'un nouveaux processus
        if [ "$( ps -A | grep -c "$pidtest")" -ge 1 ] ; then
            gettext 'The wait is too long please try again later.'
            echo ""
            rm -f $PIDFILEWAIT
            exit 2
        fi
        rm -f $PIDFILEWAIT
    fi
fi
echo $$ > $PIDFILE

noinstalldep=${noinstalldep:=0}
nomanuel=${nomanuel:=0}

SED="/bin/sed -i"
SAFE_CONF="$DIR_CONF/CTsafe.conf"
FILE_GCTOFFCONF="$DIR_CONF/GCToff.conf"
FILE_HCOMPT="$DIR_CONF/CThourscompteur"
FILE_HCONF="$DIR_CONF/CThours.conf"
## patch ssh.service pour le forcer a attendre que les interface soit bien lancer et configurée avant de démarrer.
## et éviter l'erreur suivante https://www.debian-fr.xyz/viewtopic.php?f=8&t=1445
if [ -f /lib/systemd/system/ssh.service ] ; then
    if [ "$( grep -c "network-online.target" /lib/systemd/system/ssh.service)" -eq 0 ] ; then
        $SED "s?^After=.*?After=network-online.target auditd.service?g" /lib/systemd/system/ssh.service
    fi
fi

## pour éviter les conflit avec dnsmasq
if [ -f /etc/systemd/resolved.conf ] ; then
    if [ "$( grep -c "DNSStubListener=udp" /etc/systemd/resolved.conf)" -eq 0 ] ; then
        $SED "s?.*DNSStubListener=.*?DNSStubListener=udp?g" /etc/systemd/resolved.conf
        systemctl restart systemd-resolved
    fi
fi
if [ ! -f $FILE_CONF ] ; then
    mkdir -p $DIR_CONF
    mkdir -p "$DIR_SHARE"/
    {
    echo '
LASTUPDATE=0
#LANG=fr_FR.UTF-8

## currently 3 languages are supported, English, French and Spanish.
## by default the application takes the default language of the local system or if not supported english but we can
## force with one of the following values provided you have it
## activate in the local system example under Debian via the "dpkg-reconfigure locales" command.
## possible values for LANG
## es_AR.UTF-8, es_BO.UTF-8, es_CL.UTF-8, es_CO.UTF-8
## es_CR.UTF-8, es_CU.UTF-8, es_DO.UTF-8, es_EC.UTF-8
## es_ES.UTF-8, es_GT.UTF-8, es_HN.UTF-8, es_MX.UTF-8
## es_NI.UTF-8, es_PA.UTF-8, es_PE.UTF-8, es_PR.UTF-8
## es_PY.UTF-8, es_SV.UTF-8, es_US.UTF-8, es_UY.UTF-8
## es_VE.UTF-8, en_BE.UTF-8, fr_CA.UTF-8, fr_CH.UTF-8
## en_EN.UTF-8, en_LU.UTF-8
## taking into account in the web interface requires to restart the service lighttpd

DNSMASQ=BLACK
AUTOUPDATE=OFF
HOURSCONNECT=OFF
GCTOFF=OFF
PRIVOXYDF=ON
REDIRECT=ON
# Parfeux minimal.
IPRULES=OFF
MD5DREAB=
MD5IPT=
I_WAN_IPV4=
I_WAN_IPV6=
IP_BOX_IPV4=
IP_BOX_IPV6=
IP_IWAN_IPV4=
IP_IWAN_IPV6=
DNS1v4=
DNS2v4=
DNS1v6=
DNS2v6=
'
    } > $FILE_CONF

fi

if [ ! -f $SAFE_CONF ] ; then
    {
    echo '
SAFEGOOGLE
SAFEYOUTUBE
SAFEBING
SAFEDUCK
SAFEQWANT
'
    } > $SAFE_CONF

fi

FILTRAGEISOFF="$( grep -c "DNSMASQ=OFF" $FILE_CONF )"

tempDIR="/tmp/alcasar"
tempDIRRamfs="/tmp/alcasarRamfs"
if [ ! -d $tempDIRRamfs ]; then mkdir "${tempDIRRamfs}"; fi
RougeD="\033[1;31m"
BleuD="\033[1;36m"
#VertD="\033[1;32m"
Fcolor="\033[0m"
NUMVER=${NUMVER:="$(dpkg -l ctparental | grep ii | awk '{print $3}' | cut -d "-" -f1)"}
COMMONFILEGS=${COMMONFILEGS:="common-auth"}
GESTIONNAIREDESESSIONS=${GESTIONNAIREDESESSIONS:=" login gdm lightdm slim kdm xdm lxdm gdm3 "}
FILEPAMTIMECONF=${FILEPAMTIMECONF:="/etc/security/time.conf"}
DIRPAM=${DIRPAM:="/etc/pam.d/"}
DAYS=${DAYS:="$(gettext "Monday") $(gettext "Tuesday") $(gettext "Wednesday") $(gettext "Thursday") $(gettext "Friday") $(gettext "Saturday") $(gettext "Sunday") "}
DAYS=( "$DAYS" )
DAYSPAM=( Mo Tu We Th Fr Sa Su )
DAYSSYSTEMD=( Mon Tue Wed Thu Fri Sat Sun ) 
PROXYport=${PROXYport:="8888"}
E2GUport=${E2GUport:="8080"}
PROXYuser=${PROXYuser:="privoxy"}
SRVPROXY=${SRVPROXY:="privoxy"}
FILCHANGELOGGZ=${FILCHANGELOGGZ:="/usr/share/doc/ctparental/changelog.Debian.gz"}
#### DEPENDANCES par DEFAUT #####
DEPENDANCES=${DEPENDANCES:=" console-data e2guardian dnsmasq lighttpd lighttpd-mod-magnet php-cgi libnotify-bin notification-daemon iptables-persistent rsyslog privoxy openssl libnss3-tools whiptail dnsutils rsyslog rsync openssh-server "}

#### PAQUETS EN CONFLIT par DEFAUT #####
CONFLICTS=${CONFLICTS:=" dansguardian mini-httpd apache2 firewalld "}

#### COMMANDES de services par DEFAUT #####
ADDCTDIGTEST=${ADDCTDIGTEST:="adduser --no-create-home --shell /bin/bash --disabled-password --system ctdigtest"}
CMDSERVICE=${CMDSERVICE:="service "}
SRVHTTP=${SRVHTTP:="lighttpd"}
FPMSOCK=${FPMSOCK:="$(ls /var/run/php/*.sock 2> /dev/null)"}
NGINXCONF=${NGINXCONF:="/etc/nginx/nginx.conf"}
PHPFPMCONF=${PHPFPMCONF:="/etc/php/php-fpm.d/www.conf"}
FUNCNGINXCONF=${FUNCNGINXCONF:="confnginx"}
PHPFPMrestart=${PHPFPMrestart:="systemctl restart php-fpm "}
PHPFPMenable=${PHPFPMenable:="systemctl enable php-fpm "}
SRVHTTPstart=${SRVHTTPstart:="$CMDSERVICE lighttpd start "}
SRVHTTPstop=${SRVHTTPstop:="$CMDSERVICE lighttpd stop "}
SRVHTTPrestart=${SRVHTTPrestart:="$CMDSERVICE lighttpd restart "}
DNSMASQstart=${DNSMASQstart:="$CMDSERVICE dnsmasq start "}
DNSMASQstop=${DNSMASQstop:="$CMDSERVICE dnsmasq stop "}
DNSMASQrestart=${DNSMASQrestart:="$CMDSERVICE dnsmasq restart "}
NWMANAGERstop=${NWMANAGERstop:="$CMDSERVICE network-manager stop"}
NWMANAGERstart=${NWMANAGERstart:="$CMDSERVICE network-manager start"}
NWMANAGERrestart=${NWMANAGERrestart:="$CMDSERVICE network-manager restart"}
NETWORKINGrestart=${NETWORKINGrestart:="$CMDSERVICE networking restart"}
IPTABLESsave=${IPTABLESsave:="iptables-save "}
IPTABLES6save=${IPTABLES6save:="ip6tables-save "}
IPTABLESrestore=${IPTABLESrestore:="iptables-restore "}
IPTABLES6restore=${IPTABLES6restore:="ip6tables-restore "}
IPTABLESsaveFILE=${IPTABLESsaveFILE:="/etc/CTparental/ipv4tables-save"}
IPTABLES6saveFILE=${IPTABLES6saveFILE:="/etc/CTparental/ipv6tables-save"}
IPSET=${IPSET:="/sbin/ipset "}
E2GUARDIANrestart=${E2GUARDIANrestart:="$CMDSERVICE e2guardian restart"}
PROXYrestart=${PROXYrestart:="$CMDSERVICE privoxy restart"}
RSYSLOGRESTART=${RSYSLOGRESTART:="$CMDSERVICE rsyslog restart"}
SSHstart=${SSHstart:="$CMDSERVICE ssh start"}
SSHstop=${SSHstop:="$CMDSERVICE ssh stop"}
SSHrestart=${SSHrestart:="$CMDSERVICE ssh restart"}
PING4=${PING4:="ping -4 "}
PING6=${PING6:="ping -6 "}
if [ -f "$DIR_CONF"/ctsync.conf ];then
PORTSSH=$( grep "PORTSSH=" "$DIR_CONF"/ctsync.conf | cut -d"=" -f2)
fi
PORTSSH=${PORTSSH:=22}

ENABLESSH=${ENABLESSH:="systemctl enable ssh"}
DISABLESSH=${DISABLESSH:="systemctl disable ssh"}
clientsync=0

#### LOCALISATION du fichier PID lighttpd par defaut ####
LIGHTTPpidfile=${LIGHTTPpidfile:="/var/run/lighttpd.pid"}

#### LOCALISATION du fichier de chargement de modules ####
DIRMODULESLOAD=${DIRMODULESLOAD:="/etc/modules-load.d"}
DIRMODULESPROB=${DIRMODULESPROB:="/etc/modprobe.d"}
FILEMODULESLOAD=${FILEMODULESLOAD:="$DIRMODULESLOAD/nftable.conf"}
FILEMODULESPROB=${FILEMODULESPROB:="$DIRMODULESPROB/nftable.conf"}

RSYSLOGCTPARENTAL=${RSYSLOGCTPARENTAL:="/etc/rsyslog.d/10-nftables.conf"}

#### COMMANDES D'ACTIVATION DES SERVICES AU DEMARRAGE DU PC ####
ENHTTP=${ENHTTP:=""}
ENDNSMASQ=${ENDNSMASQ:=""}
ENNWMANAGER=${ENNWMANAGER:=""}
ENIPTABLESSAVE=${ENIPTABLESSAVE:=""}
ENE2GUARDIAN=${ENE2GUARDIAN:=""}
ENPROXY=${ENPROXY:=""}
ENNETWORK=${ENNETWORK:=""}
FILESYSCTL=${FILESYSCTL:="/etc/sysctl.conf"}
DIRE2G=${DIRE2G:="/etc/e2guardian/"}
DIRE2GLANG=${DIRE2GLANG:="/usr/share/e2guardian/languages"}
NEWTEMPLETE2G=${NEWTEMPLETE2G:="$DIR_SHARE"/confe2guardian}
FILEConfe2gu=${FILEConfe2gu:=$DIRE2G"e2guardian.conf"}
FILEConfe2guf1=${FILEConfe2guf1:=$DIRE2G"e2guardianf1.conf"}
DREAB="$DIR_CONF/domaine-rehabiliter"
REABDIP="$DIR_CONF/dip-rehabiliter.conf"
IPV4REAB="$DIR_CONF/ipv4-rehabiliter"
IPV6REAB="$DIR_CONF/ipv6-rehabiliter"
E2GUXSITELIST=$DIRE2G"lists/exceptionsitelist"
DNSMASQCONF=${DNSMASQCONF:="/etc/dnsmasq.conf"}
MAINCONFHTTPD=${MAINCONFHTTPD:="/etc/lighttpd/lighttpd.conf"}
DIRCONFAVAILABLEHTTPD=${DIRCONFAVAILABLEHTTPD:="/etc/lighttpd/conf-available"}
DIRCONFENABELEDHTTPD=${DIRCONFENABELEDHTTPD:="/etc/lighttpd/conf-enabled"}
CTPARENTALCONFHTTPD=${CTPARENTALCONFHTTPD:="$DIRCONFAVAILABLEHTTPD/90-CTparental.conf"}
DIRHTML=${DIRHTML:="/var/www/CTparental"}
DIRadminHTML=${DIRadminHTML:="/var/www/CTadmin"}
PASSWORDFILEHTTPD=${PASSWORDFILEHTTPD:="${DIRadminHTML}/arp1_md5.password"}
REALMADMINHTTPD=${REALMADMINHTTPD:="admin.ct.local"}
CADIR=${CADIR:="/usr/local/share/ca-certificates/ctparental"}
UPDATECASYSTEM=${UPDATECASYSTEM:="update-ca-certificates"}
PEMSRVDIR=${PEMSRVDIR:="/etc/ssl/private"}
CMDINSTALL=""
IPTABLES=${IPTABLES:="/sbin/iptables"}
IPTABLES6=${IPTABLES6:="/sbin/ip6tables"}
ADDUSERTOGROUP=${ADDUSERTOGROUP:="gpasswd -a "}
DELUSERTOGROUP=${DELUSERTOGROUP:="gpasswd -d "}
ETCPRIVOXY=${ETCPRIVOXY:="/etc/privoxy"}
PRIVOXYCONF=${PRIVOXYCONF:="$ETCPRIVOXY/config"}
PRIVOXYUSERA=${PRIVOXYUSERA:="$ETCPRIVOXY/user.action"}
PRIVOXYCTA=${PRIVOXYCTA:="$ETCPRIVOXY/ctparental.action"}
TINYPROXYCONF=${TINYPROXYCONF:="/etc/tinyproxy/tinyproxy.conf"}
XSESSIONFILE=${XSESSIONFILE:="/etc/X11/Xsession"}
REPCAMOZ=${REPCAMOZ:="/usr/share/ca-certificates/mozilla/"}
DOMAINEDEPOTS=${DOMAINEDEPOTS:=$(cat /etc/apt/sources.list /etc/apt/sources.list.d/* 2>/dev/null | grep "^deb" | cut -d"/" -f3 | sort -u | sed -e "s/^www././g" )}
TIMERALERT=${TIMERALERT:=10}
NEWPASSGRUB2=${NEWPASSGRUB2:="grub-mkpasswd-pbkdf2"}
BOOTREPGRUB2=${BOOTREPGRUB2:="/boot/grub"}
BL_SERVER="dsi.ut-capitole.fr"
BL_T=${BL_T:="http://$BL_SERVER/blacklists/download/blacklists.tar.gz"}
BL_CT=${BL_CT:="https://gitlab.com/marsat/bl_ctparental/raw/master/blacklists2.tar.gz"}
## BL_DIPOSSI contien la blacklist ossi avec les noms de domaine les ipv6 et les ipv4 que l'on veut ajouter 
## ne bloque que les utilisateurs filtrés
BL_DIPOSSI="$DIR_CONF/dip-blackliste.conf"
## FILEIPBLACKLIST ne se configure que en manuel et bloque tous le mondes même root
FILEIPBLACKLIST="$DIR_CONF/ip-blackliste.conf"
FILEFIRWALLCONF="$DIR_CONF/iptables.conf"
FILEIPTIMEWEB="$DIR_CONF/iptables-timerweb"
CATEGORIES_ENABLED="$DIR_CONF/categories-enabled.conf"
BL_CATEGORIES_AVAILABLE="$DIR_CONF/bl-categories-available"
WL_CATEGORIES_AVAILABLE="$DIR_CONF/wl-categories-available"
DIR_DNS_FILTER_AVAILABLE="$DIR_CONF/dnsfilter-available"
DIR_IPV4_FILTER_AVAILABLE="$DIR_CONF/ipv4filter-available"
DIR_IPV6_FILTER_AVAILABLE="$DIR_CONF/ipv6filter-available"
DIR_IPV4_FILTER_ENABLED="$DIR_CONF/ipv4filter-enable"
DIR_IPV6_FILTER_ENABLED="$DIR_CONF/ipv6filter-enable"
DIR_DNS_BLACKLIST_ENABLED="$DIR_CONF/blacklist-enabled"
DIR_DNS_WHITELIST_ENABLED="$DIR_CONF/whitelist-enabled"
THISDAYS=$(( $(date +%Y) * 365 + $(date +%j | sed -e "s/^0*//g") ))
USERHTTPD=${USERHTTPD:=$( grep /var/www /etc/passwd  | cut -d":" -f1)}
GROUPHTTPD=${GROUPHTTPD:=$( grep "$USERHTTPD" /etc/group | cut -d":" -f1)}


if [ "$(yum help 2> /dev/null | wc -l )" -ge 50 ] ; then
    ## "Distribution basée sur yum exemple redhat, fedora..."
    CMDINSTALL=${CMDINSTALL:="yum install "}
    CMDREMOVE=${CMDREMOVE:="rpm -e "}
fi
urpmi --help > /dev/null 2>&1
if [ $? -eq 1 ] ; then
    ## "Distribution basée sur urpmi exemple mandriva..."
    CMDINSTALL=${CMDINSTALL:="urpmi -a --auto "}
    CMDREMOVE=${CMDREMOVE:="rpm -e "}
fi
apt-get -h > /dev/null 2>&1
if [ $? -eq 0 ] ; then
    ## "Distribution basée sur apt-get exemple debian, ubuntu ..."
    CMDINSTALL=${CMDINSTALL:="apt-get -y --force-yes install "}
    CMDREMOVE=${CMDREMOVE:="dpkg --purge  "}
fi

eopkg --help > /dev/null 2>&1
if [ $? -eq 1 ] ; then
    ## "Distribution basée sur eopkg exemple Solus..."
    CMDINSTALL=${CMDINSTALL:="eopkg install "}
    CMDREMOVE=${CMDREMOVE:="eopkg remove "}
fi

if [ -z "$CMDINSTALL" ] ; then
    gettext 'No known package manager was detected.'
    set -e
    exit 1
fi
if [ "${1}" = "-i" ];then
$ADDCTDIGTEST
fi
source "$DIR_SHARE/ConfLanIs"

function ipV4ok() {
    ip=$(echo "$1" | cut -d"/" -f1)
    mask=$(echo "$1" | grep "/" | cut -d"/" -f2)
    if [ "$(echo "$1" | grep -c "^\(\(2[0-5][0-5]\|2[0-4][0-9]\|1[0-9][0-9]\|[0-9]\{1,2\}\)\.\)\{3\}\(2[0-5][0-5]\|2[0-4][0-9]\|1[0-9][0-9]\|[0-9]\{1,2\}\)$")" -eq 1 ];then
        echo 1
        return 1
    fi
    if [ ! "$(echo "$ip" | grep -c "^\(\(2[0-5][0-5]\|2[0-4][0-9]\|1[0-9][0-9]\|[0-9]\{1,2\}\)\.\)\{3\}\(2[0-5][0-5]\|2[0-4][0-9]\|1[0-9][0-9]\|[0-9]\{1,2\}\)$")" -eq 1 ];then
        echo 0
        return 0
    fi
    if [ "$(echo "$mask" | grep -c "^\([1-9]\|[1-2][0-9]\|3[0-2]\)$")" -eq 1 ];then
        echo 1
        return 1
    fi
    i=1
    octn=255
    result=1
while [ $i -le 4 ]
do
    oct=$( echo "$mask" | grep '\.'| cut -d "." -f$i )
    if [ -z "$oct" ] ; then
        result=0
        break
    fi
    if [ ! "$octn" -eq 255 ];then
        if [ ! "$oct" -eq 0 ];then
            result=0
            break
        fi
    fi
    octn=$oct
    if [ ! "$oct" -eq 255 ] &&  [ ! "$oct" -eq 254 ]  &&  [ ! "$oct" -eq 252 ] &&  [ ! "$oct" -eq 248 ] &&  [ ! "$oct" -eq 240 ] &&  [ ! "$oct" -eq 224 ] &&  [ ! "$oct" -eq 192 ] &&  [ ! "$oct" -eq 128 ] &&  [ ! "$oct" -eq 0 ]; then
        result=0
        break
      fi
    i=$(( i + 1 ))
done
    echo $result
    return $result
}

function ipV6ok (){
ip=$(echo "$1" | cut -d"/" -f1)
mask=$(echo "$1" | grep "/" | cut -d"/" -f2) # de 1 a 128
if [ $(echo $ip | grep -Ec "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$" ) -eq 0 ] ;then
echo 0
return 0
fi
if [ "$(echo "$mask" | grep -c "^\([1-9]\|[1-9][0-9]\|[1][0-1][0-9]\|[1][2][0-8]\)$")" -eq 1 ];then
    echo 1
    return 1
fi
if [ -z "$mask" ];then
    echo 1
    return 1
fi
echo 0
return 0
}

function iptdisableconflict() {
        ## on desactive firewalld pour eviter les conflit avec nftables
        if [ $(systemctl list-unit-files | grep -c "firewalld.service") -ge 1 ];then
            if [ $(systemctl is-enabled firewalld.service ) != "masked" ] ; then
                systemctl stop firewalld.service
                systemctl disable firewalld.service
                systemctl mask firewalld.service
            fi
        fi
        if [ $(systemctl list-unit-files | grep -c "iptables.service") -ge 1 ];then
            if [ $(systemctl is-enabled iptables.service ) != "masked" ] ; then
                systemctl stop iptables.service
                systemctl disable iptables.service
                systemctl mask iptables.service
            fi
        fi
        if [ $(systemctl list-unit-files | grep -c "ip6tables.service") -ge 1 ];then
            if [ $(systemctl is-enabled ip6tables.service ) != "masked" ] ; then
                systemctl stop ip6tables.service
                systemctl disable ip6tables.service
                systemctl mask ip6tables.service
            fi
        fi
        if [ $(systemctl list-unit-files | grep -c "shorewall.service") -ge 1 ];then
            if [ $(systemctl is-enabled shorewall.service ) != "masked" ] ; then
                systemctl stop shorewall.service
                systemctl disable shorewall.service
                systemctl mask shorewall.service
            fi
        fi
        if [ $(systemctl list-unit-files | grep -c "shorewall6.service") -ge 1 ];then
            if [ $(systemctl is-enabled shorewall6.service ) != "masked" ] ; then
                systemctl stop shorewall6.service
                systemctl disable shorewall6.service
                systemctl mask shorewall6.service
            fi
        fi
        if [ $(systemctl list-unit-files | grep -c "nftables.service") -ge 1 ];then
            if [ $(systemctl is-enabled nftables.service ) != "masked" ] ; then
                systemctl stop nftables.service
                systemctl disable nftables.service
                systemctl mask nftables.service
            fi
        fi
        if [ $(systemctl list-unit-files | grep -c "ufw.service") -ge 1 ];then
            if [ $(systemctl is-enabled ufw.service ) != "masked" ] ; then
                systemctl stop ufw.service
                systemctl disable ufw.service
                systemctl mask ufw.service
            fi
        fi
        if [ $(systemctl list-unit-files | grep -c "netfilter-persistent.service") -ge 1 ];then
            if [ $(systemctl is-enabled netfilter-persistent.service ) != "masked" ] ; then
                systemctl stop netfilter-persistent.service
                systemctl disable netfilter-persistent.service
                systemctl mask netfilter-persistent.service
            fi
        fi
        if [ $(systemctl list-unit-files | grep -c "iptables-persistent.service") -ge 1 ];then
            if [ $(systemctl is-enabled iptables-persistent.service ) != "masked" ] ; then
                systemctl stop iptables-persistent.service
                systemctl disable iptables-persistent.service
                systemctl mask iptables-persistent.service
            fi
        fi
}

function pingok() {
    ipv4ok=0
    $PING4 -c1 -w1 "$1" 2>/dev/null 1>/dev/null
    if [ $? -eq  0 ];then
    ipv4ok=1
    fi

    ipv6ok=0
    $PING6 -c1 -w1 "$1" 2>/dev/null 1>/dev/null
    if [ $? -eq  0 ];then
    ipv6ok=1
    fi

    if [ $ipv4ok -eq 0 ];then
        if [ $ipv6ok -eq 0 ];then
            echo 0
            return 0
        else
            echo 1
            return 1
        fi
    else
        echo 1
        return 1
    fi
}

function networkisoknext() {
    ipv4ok=0
    $PING4 -c1 -w1 "$ipbox_ipv4" 2>/dev/null 1>/dev/null
    if [ $? -eq  0 ];then
    ipv4ok=1
    fi

    ipv6ok=0
    $PING6 -c1 -w1 "$ipbox_ipv6" 2>/dev/null 1>/dev/null
    if [ $? -eq  0 ];then
    ipv6ok=1
    fi

    if [ $ipv4ok -eq 0 ];then
    if [ $ipv6ok -eq 0 ];then
       gettext 'error recovering network settings'
       echo
       exit 0
    fi
    fi
}

function resolvconffixon() {
    echo "<resolvconffixon>"
    # redémarre dnsmasq
    $DNSMASQstop
    resolvconf -u > /dev/null 2>&1
    if [ $? -eq 0 ];then # si resolvconf est bien installé
        if [ -d /etc/resolvconf ];then
        resolvconf -u
        # on s'assure que les dns du FAI soient bien ajoutés au
        # fichier /etc/resolv.conf malgré l'utilisation de dnsmasq.
        grep ^nameserver /etc/resolv.conf | grep -v 127.0.0.1 | sort -u > /etc/resolvconf/resolv.conf.d/tail
        sleep 1
        fi
    fi
    $DNSMASQstart
    echo "</resolvconffixon>"
}

function resolvconffixoff() {
    echo "<resolvconffixoff>"
    $DNSMASQstop
    resolvconf -u > /dev/null 2>&1
    if [ $? -eq 0 ];then # si resolvconf est bien installé
        if [ -d /etc/resolvconf ];then
        echo > /etc/resolvconf/resolv.conf.d/tail
        resolvconf -u
        fi
    fi
    echo "</resolvconffixoff>"
}


PRIVATE_IP4="127.0.0.10"
PRIVATE_IP6="fd00::127:10"
ADMIN_IP4="127.0.0.11"
ADMIN_IP6="fd00::127:11"



FILE_tmp=${FILE_tmp:="$tempDIRRamfs/filetmp.txt"}
FILE_tmpSizeMax=${FILE_tmpSizeMax:="256M"}  # 70 Min, Recommend 128M
LOWRAM=${LOWRAM:=0}
if [ "$LOWRAM" -eq 0 ] ; then
    MFILEtmp="mount -t tmpfs -o size=$FILE_tmpSizeMax tmpfs $tempDIRRamfs"
    UMFILEtmp="umount $tempDIRRamfs"
else
    MFILEtmp=""
    UMFILEtmp=""
fi


function initblenabled() {
    {
    echo 'adult
adultsearchengine
agressif
ctparental
dangerous_material
cryptojacking
dating
drogue
gambling
hacking
malware
marketingware
mixed_adult
phishing
redirector
publicite
ddos
sect
strict_redirector
strong_redirector
tricheur
warez
tor_nodes
ossi'
    } > $CATEGORIES_ENABLED
    chown root:"$GROUPHTTPD" "$CATEGORIES_ENABLED"
    chmod 664 "$CATEGORIES_ENABLED"
}

function confe2guardian() {
    # replace the default deny HTML page
    echo "<confe2guardian>"
    $SED "s?^loglevel =.*?loglevel = 0?g" "$FILEConfe2gu"
    $SED "s?^languagedir =.*?languagedir = \'$DIRE2GLANG\'?g" "$FILEConfe2gu"
    $SED "s?^language =.*?language = 'french'?g" "$FILEConfe2gu"
    $SED "s?^logexceptionhits =.*?logexceptionhits = 0?g" "$FILEConfe2gu"
    $SED "s?^filterip =.*?filterip = 127.0.0.1?g" "$FILEConfe2gu"
    $SED "s?^proxyip =.*?proxyip = 127.0.0.1?g" "$FILEConfe2gu"
    $SED "s?^#proxyip =.*?proxyip = 127.0.0.1?g" "$FILEConfe2gu"
    $SED "s?^filterports =.*?filterports = $E2GUport?g" "$FILEConfe2gu"
    $SED "s?^proxyport =.*?proxyport = $PROXYport?g" "$FILEConfe2gu"
    $SED "s?^#proxyport =.*?proxyport = $PROXYport?g" "$FILEConfe2gu"
    $SED "s?^proxyport =transparenthttpsport =.*?#transparenthttpsport = 8443?"  "$FILEConfe2gu"
    $SED "s?^proxytimeout =.*?proxytimeout = 10?"  "$FILEConfe2gu"
    $SED "s?^connecttimeout =.*?connecttimeout = 10?"  "$FILEConfe2gu"
    $SED "s?.*UNCONFIGURED.*?#UNCONFIGURED?g" "$FILEConfe2gu"
    {
    echo "
#Blanket Block.  To block all sites except those in the
#exceptionsitelist and greysitelist files, remove
#the # from the next line to leave only a '**':
#**

#Blanket SSL/CONNECT Block.  To block all SSL
#and CONNECT tunnels except to addresses in the
#exceptionsitelist and greysitelist files, remove
#the # from the next line to leave only a '**s':
#**s

#Blanket IP Block.  To block all sites specified only as an IP,
#remove the # from the next line to leave only a '*ip':
#*ip

#Blanket SSL/CONNECT IP Block.  To block all SSL and CONNECT
#tunnels to sites specified only as an IP,
#remove the # from the next line to leave only a '**ips':
#**ips

$(gettext "#the domain filtering is handled by dnsmasq, do not touch this file!")
"
    } > "$DIRE2G"lists/bannedsitelist
    $E2GUARDIANrestart
    cp -f "$NEWTEMPLETE2G"/template.html "$DIRE2GLANG"/ukenglish/
    cp -f "$NEWTEMPLETE2G"/template-fr.html "$DIRE2GLANG"/french/template.html
    sed -i "s/é/\&eacute;/g" "$DIRE2GLANG"/french/messages
    sed -i "s/è/\&egrave;/g" "$DIRE2GLANG"/french/messages
    $E2GUARDIANrestart
    echo "</confe2guardian>"
}

function privoxydefaultfilteroff() {
    $SED "s?^PRIVOXYDF.*?PRIVOXYDF=OFF?g" $FILE_CONF
    $SED "s?^actionsfile match-all.action.*?#actionsfile match-all.action?g" "$PRIVOXYCONF"
    $SED "s?^actionsfile default.action.*?#actionsfile default.action?g" "$PRIVOXYCONF"
    $SED "s?^filterfile default.filter.*?#filterfile default.filter?g" "$PRIVOXYCONF"
    $PROXYrestart
}

function privoxydefaultfilteron() {
    $SED "s?^PRIVOXYDF.*?PRIVOXYDF=ON?g" $FILE_CONF
    $SED "s?#actionsfile match-all.action.*?actionsfile match-all.action?g" "$PRIVOXYCONF"
    $SED "s?#actionsfile default.action.*?actionsfile default.action?g" "$PRIVOXYCONF"
    $SED "s?#filterfile default.filter.*?filterfile default.filter?g" "$PRIVOXYCONF"
    $PROXYrestart
}

function conftinyproxy() {
    echo "<conftinyproxy>"
    $SED "s?^Port .*?Port 8888?" "$TINYPROXYCONF"
    $SED "s?^Listen .*?Port Listen 127.0.0.1?" "$TINYPROXYCONF"
    echo "</conftinyproxy>"
}

function confproxy() {
if [ $SRVPROXY = "privoxy" ] ; then
    confprivoxy
fi
if [ $SRVPROXY = "tinyproxy" ] ; then
    conftinyproxy
fi
}

function confprivoxy() {
    echo "<confprivoxy>"
    $SED "s?^debug.*?debug = 0?g"  "$PRIVOXYCONF"
    test=$( grep -c "^listen-address.*" "$PRIVOXYCONF" )
    ligneipv4=$( sed -n '/^listen-address.*/=' "$PRIVOXYCONF" | sed '1q;d' )
    if [ "$test" -eq "1" ] ; then
    ligneipv6=$((ligneipv4 + 1))
    $SED "$ligneipv4 s?^listen-address.*?listen-address  127.0.0.1:$PROXYport?"  "$PRIVOXYCONF"
    $SED "$ligneipv6""i\listen-address  [::1]:$PROXYport" "$PRIVOXYCONF"
    else
    ligneipv6=$( sed -n '/^listen-address.*/=' "$PRIVOXYCONF" | sed '2q;d' )
    $SED "$ligneipv4 s?^listen-address.*?listen-address  127.0.0.1:$PROXYport?"  "$PRIVOXYCONF" #ipv4
    $SED "$ligneipv6 s?^listen-address.*?listen-address  [::1]:$PROXYport?"  "$PRIVOXYCONF" #ipv6
    fi
    unset test
    test=$(grep -c "actionsfile ctparental.action" "$PRIVOXYCONF" )
    if [ "$test" -ge "1" ] ; then
    $SED "s?actionsfile.*ctparental.*?actionsfile ctparental\.action      # ctparental customizations?g" "$PRIVOXYCONF"
    else
    nline=$(grep "actionsfile.*user.action" "$PRIVOXYCONF" -n | cut -d":" -f1)
    $SED "$nline""i\actionsfile ctparental.action      # ctparental customizations" "$PRIVOXYCONF"
    fi
    $SED "s?^accept-intercepted-requests.*?accept-intercepted-requests 1 ?" "$PRIVOXYCONF"
    $SED "s?^keep-alive-timeout.*?keep-alive-timeout 20 ?" "$PRIVOXYCONF"
    $SED "s?^#.*receive-buffer-size 32768?receive-buffer-size 32768?" "$PRIVOXYCONF"
    unset test
    {
    echo '{{alias}}
+crunch-all-cookies = +crunch-incoming-cookies +crunch-outgoing-cookies
-crunch-all-cookies = -crunch-incoming-cookies -crunch-outgoing-cookies
 allow-all-cookies  = -crunch-all-cookies -session-cookies-only -filter{content-cookies}
 allow-popups       = -filter{all-popups} -filter{unsolicited-popups}
+block-as-image     = +block{Blocked image request.} +handle-as-image
-block-as-image     = -block
fragile     = -block -crunch-all-cookies -filter -fast-redirects -hide-referer -prevent-compression
shop        = -crunch-all-cookies allow-popups
myfilters   = +filter{html-annoyances} +filter{js-annoyances} +filter{all-popups}\
              +filter{webbugs} +filter{banners-by-size}
allow-ads   = -block -filter{banners-by-size} -filter{banners-by-link}
{ fragile }
http://admin.ct.local.*
http://privet.ct.local.*
http://localhost.*
# BING Add &adlt=strict
{+redirect{s@$@&adlt=strict@}}
.bing./.*[&?]q=
{-redirect}
.bing./.*&adlt=strict

{+redirect{s@http://.*/images/close.*.png@http://privet.ct.local/images/X32px.png@}}
.*

{+redirect{s@http://.*/close.*.png@http://privet.ct.local/images/X32px.png@}}
.*

'
    } >  $PRIVOXYCTA

    $PROXYrestart
    echo "</confprivoxy>"
}

function  gensalt() {   
local length=${1:-8}
tr -dc A-Za-z0-9_ < /dev/urandom | head -c "${length}" | xargs
}

function addadminhttpdapr1md5php () {
    if [ ! -f "$PASSWORDFILEHTTPD" ]; then touch "$PASSWORDFILEHTTPD"; fi
    USERADMINHTTPD=${1}
    pass=${2}
    echo -n "${USERADMINHTTPD}:" > "$PASSWORDFILEHTTPD"
    openssl passwd -apr1 -salt "$(gensalt)" "${pass}" >> "$PASSWORDFILEHTTPD"
    chown root:"$USERHTTPD" "$PASSWORDFILEHTTPD"
    chmod 640 "$PASSWORDFILEHTTPD"
}


function download() {
    rm -rf $tempDIR
    mkdir $tempDIR
    # on attend que la connection remonte suite au redémarrage de networkmanager
    gettext 'Waiting to connect to Toulouse server:'
    i=1
    while [ "$(pingok "$BL_SERVER" )" -eq 0 ]
    do
    echo -n .
    sleep 1
    i=$(( i + 1 ))
    # si au bout de 40 secondes on n'a toujours pas de connection on considère qu'il y a une erreur
    if [ $i -ge 40 ];then
       gettext 'Connection to Toulouse server is impossible.'
       set -e
       exit 1
    fi
    done
    echo
    gettext 'connection established:'

    wget -P $tempDIR $BL_T 2>&1 | cat
    if [ ! $? -eq 0 ]; then
        gettext 'error when downloading, process interrupted'
        rm -rf $tempDIR
        set -e
        exit 1
    fi
    tarfile=$(basename "$BL_T")
    tar -xzf "$tempDIR/$tarfile" -C $tempDIR
    if [ ! $? -eq 0 ]; then
        gettext 'archive extraction error, process interrupted'
        set -e
        exit 1
    fi
    # on télécharge aussi la blacklist personalisée de ctparental
    wget -P $tempDIR $BL_CT 2>&1 | cat
    if [ ! $? -eq 0 ]; then
        gettext 'error when downloading, process interrupted'
        rm -rf $tempDIR
        set -e
        exit 1
    fi
    tarfile=$(basename "$BL_CT")
    tar -xzf "$tempDIR/$tarfile" -C $tempDIR
    if [ ! $? -eq 0 ]; then
        gettext 'archive extraction error , process interrupted'
        set -e
        exit 1
    fi
    rm -rf ${DIR_DNS_FILTER_AVAILABLE:?}/
    mkdir $DIR_DNS_FILTER_AVAILABLE
    rm -rf ${DIR_IPV4_FILTER_AVAILABLE:?}/ 
    mkdir $DIR_IPV4_FILTER_AVAILABLE
    rm -rf ${DIR_IPV6_FILTER_AVAILABLE:?}/  
    mkdir $DIR_IPV6_FILTER_AVAILABLE
    $SED "s?^MD5DREAB.*?MD5DREAB=?g" $FILE_CONF
}

function autoupdateon() {
    $SED "s?^AUTOUPDATE.*?AUTOUPDATE=ON?g" $FILE_CONF

    {
     echo "[Unit]
Description=updates parental control from the blacklist of the University of Toulouse
After=network-online.target


[Service]
User=root
WorkingDirectory=/root/
ExecStart=$CHEMINCTPARENTLE -dl
Type=oneshot

[Install]
WantedBy=default.target

"
} > /etc/systemd/system/CTparentalaup.service
# on redémare le démon systemd pour prendre en compte ce nouveau service
systemctl daemon-reload
{
echo "
[Unit]
Description=updates parental control from the blacklist of the University of Toulouse every week

[Timer]
# on attent 5 minute après le boot
OnBootSec=5min
# toute les semaines
OnUnitActiveSec=1w
# Autoriser la persistence entre les reboot
Persistent=true
[Install]
WantedBy=timers.target
"
} > /etc/systemd/system/CTparentalaup.timer
systemctl enable CTparentalaup.timer
systemctl start CTparentalaup.timer

}

function autoupdateoff() {
     $SED "s?^AUTOUPDATE.*?AUTOUPDATE=OFF?g" $FILE_CONF
     systemctl disable CTparentalaup.timer
     systemctl stop CTparentalaup.timer
     rm -f /etc/systemd/system/CTparentalaup.service
     rm -f /etc/systemd/system/CTparentalaup.timer
     # on redémare le démon systemd pour prendre en compte ce nouveau service
     systemctl daemon-reload

}

function adapt() {
    echo "<adapt>"
    date +%H:%M:%S
    dnsmasqoff
    $MFILEtmp
    if [ ! -f $BL_DIPOSSI ] ; then
       echo > $BL_DIPOSSI
    fi
    if [ -d $tempDIR  ] ; then
        CATEGORIES_AVAILABLE="$tempDIR"/categories_available
        echo -n > $CATEGORIES_AVAILABLE
        echo -n > $WL_CATEGORIES_AVAILABLE
        echo -n > $BL_CATEGORIES_AVAILABLE
        if [ ! -f $DIR_DNS_FILTER_AVAILABLE/ossi.conf ] ; then
            echo > $DIR_DNS_FILTER_AVAILABLE/ossi.conf
        fi
        if [ ! -f $DIR_IPV4_FILTER_AVAILABLE/ossi.conf ] ; then
            echo > $DIR_IPV4_FILTER_AVAILABLE/ossi.conf
        fi
        if [ ! -f $DIR_IPV6_FILTER_AVAILABLE/ossi.conf ] ; then
            echo > $DIR_IPV6_FILTER_AVAILABLE/ossi.conf
        fi
        gettext 'Toulouse Blacklist and WhiteList migration process. Please wait.'
        cd "$tempDIR"/blacklists
        for categorie in *
        do
            if [ -d "$categorie" ] ; then
            if [ ! -L "$categorie" ] ; then
                echo "$categorie" >> $CATEGORIES_AVAILABLE
                echo -n "."
                grep -E "^(((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2}).){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2}))($|/(([1-9])|([1-2][0-9])|(3[0-2]))$)" "$tempDIR"/blacklists/"$categorie"/domains | sed  "s/^/add ipv4filter /"  > $DIR_IPV4_FILTER_AVAILABLE/"$categorie".conf
                grep -E "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))($|/(([1-9])|([1-9][0-9])|(1[0-1][0-9])|(12[0-8]))$)" "$tempDIR"/blacklists/"$categorie"/domains | sed  "s/^/add ipv6filter /" > $DIR_IPV6_FILTER_AVAILABLE/"$categorie".conf
                #cp -f "$tempDIR"/blacklists/"$categorie"/domains "$FILE_tmp"
                ## on ne garde que les nom de domaine valide (suppressions ivpv4 ipv6 les entrée xx.blogspot.xx ..)
                ## supprime xx--xxxx , -xxxx , xxxx-.xxxx , #xxxx , ligne vide , ligne contenent de caractèrs spéciaux 
                ## voir https://www.generation-nt.com/reponses/nom-domaine-caracteres-speciaux-entraide-231588.html#943863
                ## on supprime les 1313541 entrées xx.blogspot.xx
                ## dans la catégorie adult qui sont gérées par
                ## une liste beaucoup plus courte dans la
                ## catégorie ctparental
                grep -vE  "^(.{2}--)|^(.*-\.)|^(-)|^(#)|[äâëêïîöôüûàçèé&\!@,]|^$|.*blogspot\..*|^((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})\.){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})$" "$tempDIR"/blacklists/"$categorie"/domains | grep -vE "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$" | awk '{ gsub("\\.+\\.",".");print }' > "$FILE_tmp"
                ## on corrige les erreurs eventuel de .. qui ce suivent sans rien entre faisent planter dnsmasq
                #$SED "s/\.\{2,10\}/\./" "$FILE_tmp"
                if [ -e "$tempDIR"/blacklists/"$categorie"/usage ] ; then
                    if [ "$(grep -c "white" "$tempDIR"/blacklists/"$categorie"/usage)" -ge 1 ] ;then
                        echo "$categorie" >> $WL_CATEGORIES_AVAILABLE
                        # Mise en forme dnsmasq des listes blanches
                        awk  '{ sub(/.*/, "address=/&/#") ; print }' "$FILE_tmp" > "$DIR_DNS_FILTER_AVAILABLE"/"$categorie".conf
                        #$SED "s?.*?server=/&/#?" "$FILE_tmp"
                        #mv "$FILE_tmp" "$DIR_DNS_FILTER_AVAILABLE"/"$categorie".conf
                    else
                        echo "$categorie" >> $BL_CATEGORIES_AVAILABLE
                        # Mise en forme dnsmasq des listes noires
                        awk  -v var="$PRIVATE_IP4" '{ sub(/.*/, "address=/&/"var) ; print }' "$FILE_tmp" > "$DIR_DNS_FILTER_AVAILABLE"/"$categorie".conf
                        #$SED "s?.*?address=/&/$PRIVATE_IP4?" "$FILE_tmp"
                        #mv "$FILE_tmp" "$DIR_DNS_FILTER_AVAILABLE"/"$categorie".conf
                    fi
                else
                    echo "$categorie" >> $BL_CATEGORIES_AVAILABLE
                    # Mise en forme dnsmasq des listes noires
                    awk  -v var="$PRIVATE_IP4" '{ sub(/.*/, "address=/&/"var) ; print }' "$FILE_tmp" > "$DIR_DNS_FILTER_AVAILABLE"/"$categorie".conf
                    #$SED "s?.*?address=/&/$PRIVATE_IP4?" "$FILE_tmp"
                    #mv "$FILE_tmp" "$DIR_DNS_FILTER_AVAILABLE"/"$categorie".conf
                fi
            fi
            fi
        done
        echo -n "."
        ## gestion de la blacklist ossi (ipv4 + ipv6 + dns) 
        # suppression des @IP, de caractères acccentués et des lignes commentées ou vides
        ##cp -f $BL_DIPOSSI "$FILE_tmp"
        grep -E "^(((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2}).){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2}))($|/(([1-9])|([1-2][0-9])|(3[0-2]))$)" $BL_DIPOSSI | sed  "s/^/add ipv4filter /" > $DIR_IPV4_FILTER_AVAILABLE/ossi.conf
        grep -E "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))($|/(([1-9])|([1-9][0-9])|(1[0-1][0-9])|(12[0-8]))$)" $BL_DIPOSSI | sed  "s/^/add ipv6filter /" > $DIR_IPV6_FILTER_AVAILABLE/ossi.conf
        grep -vE  "^(.{2}--)|^(.*-\.)|^(-)|^(#)|[äâëêïîöôüûàçèé&\!@,]|^$|.*blogspot\..*|^((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})\.){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})$" $BL_DIPOSSI | grep -vE "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$" | awk  -v var="$PRIVATE_IP4" '{ sub(/.*/, "address=/&/"var) gsub("\\.+\\.",".") ; print }' > "$DIR_DNS_FILTER_AVAILABLE"/ossi.conf
        #$SED "s/\.\{2,10\}/\./" "$FILE_tmp"
        # Mise en forme dnsmasq
        #$SED "s?.*?address=/&/$PRIVATE_IP4?" "$FILE_tmp"
        #mv "$FILE_tmp" "$DIR_DNS_FILTER_AVAILABLE"/ossi.conf
    else
        mkdir   $tempDIR
        echo -n "."
        ## gestion de la blacklist ossi (ipv4 + ipv6 + dns) 
        # suppression des @IP, de caractères acccentués et des lignes commentées ou vides
        grep -E "^(((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2}).){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2}))($|/(([1-9])|([1-2][0-9])|(3[0-2]))$)" $BL_DIPOSSI | sed  "s/^/add ipv4filter /" > $DIR_IPV4_FILTER_AVAILABLE/ossi.conf
        grep -E "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))($|/(([1-9])|([1-9][0-9])|(1[0-1][0-9])|(12[0-8]))$)" $BL_DIPOSSI | sed  "s/^/add ipv6filter /" > $DIR_IPV6_FILTER_AVAILABLE/ossi.conf
        grep -vE  "^(.{2}--)|^(.*-\.)|^(-)|^(#)|[äâëêïîöôüûàçèé&\!@,]|^$|.*blogspot\..*|^((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})\.){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})$" $BL_DIPOSSI | grep -vE "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$" | awk '{ gsub("\\.+\\.",".");print }' > "$FILE_tmp"
        # $SED "s/\.\{2,10\}/\./" "$FILE_tmp"
        # Mise en forme dnsmasq
        awk  -v var="$PRIVATE_IP4" '{ sub(/.*/, "address=/&/"var) ; print }' "$FILE_tmp" > "$DIR_DNS_FILTER_AVAILABLE"/ossi.conf
        #$SED "s?.*?address=/&/$PRIVATE_IP4?" "$FILE_tmp"
        #mv "$FILE_tmp" "$DIR_DNS_FILTER_AVAILABLE"/ossi.conf
    fi
    echo
    $UMFILEtmp
    cd "$(dirname "$(readlink -f "$0")")"
    rm -rf $tempDIR
    date +%H:%M:%S
    echo "</adapt>"
}

function catChoice() {
    echo "<catChoice>"
    if [ ! -f $REABDIP ] ; then
        echo > "$REABDIP"
    fi
    md5old=$(grep MD5DREAB= "$FILE_CONF" | cut -d"=" -f2)
    md5new="$({
cat "$REABDIP" "$CATEGORIES_ENABLED" "$SAFE_CONF"
echo "$DOMAINEDEPOTS"
md5sum $DIR_DNS_FILTER_AVAILABLE/* | grep -v ossi.conf
md5sum $DIR_IPV6_FILTER_AVAILABLE/* | grep -v ossi.conf
md5sum $DIR_IPV4_FILTER_AVAILABLE/* | grep -v ossi.conf
} | md5sum )"
     ## évite de lancer la moulinette de réhabilitation des domaines
     ## quand aucun changement ne le nécéssite.
     if [ ! "$md5old" = "$md5new" ]; then
    rm -rf ${DIR_DNS_BLACKLIST_ENABLED:?}/
    mkdir $DIR_DNS_BLACKLIST_ENABLED
    rm -rf  ${DIR_DNS_WHITELIST_ENABLED:?}/
    mkdir  $DIR_DNS_WHITELIST_ENABLED
    rm -rf ${DIR_IPV6_FILTER_ENABLED:?}/
    mkdir $DIR_IPV6_FILTER_ENABLED
    rm -rf ${DIR_IPV4_FILTER_ENABLED:?}/
    mkdir $DIR_IPV4_FILTER_ENABLED
    while read CATEGORIE
    do
        if [ "$(grep -c "$CATEGORIE" "$BL_CATEGORIES_AVAILABLE")" -ge "1" ] ; then
        cp $DIR_DNS_FILTER_AVAILABLE/"$CATEGORIE".conf $DIR_DNS_BLACKLIST_ENABLED/
        cp $DIR_IPV6_FILTER_AVAILABLE/"$CATEGORIE".conf $DIR_IPV6_FILTER_ENABLED/
        cp $DIR_IPV4_FILTER_AVAILABLE/"$CATEGORIE".conf $DIR_IPV4_FILTER_ENABLED/
        else
        cp $DIR_DNS_FILTER_AVAILABLE/"$CATEGORIE".conf $DIR_DNS_WHITELIST_ENABLED/
        fi
    done < $CATEGORIES_ENABLED
    reabdomaine
    $SED "s?^MD5DREAB.*?MD5DREAB=$md5new?" $FILE_CONF
    fi
    cp $DIR_DNS_FILTER_AVAILABLE/ossi.conf $DIR_DNS_BLACKLIST_ENABLED/
    cp $DIR_IPV6_FILTER_AVAILABLE/ossi.conf $DIR_IPV6_FILTER_ENABLED/
    cp $DIR_IPV4_FILTER_AVAILABLE/ossi.conf $DIR_IPV4_FILTER_ENABLED/
    iptablesreload
    echo "</catChoice>"
}

function reabdomaine() {
    echo "<reabdomaine>"
    date +%H:%M:%S
    $MFILEtmp
    if [ ! -f $REABDIP ] ; then
    echo > "$REABDIP"
    fi
    grep -E "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))($|/(([1-9])|([1-9][0-9])|(1[0-1][0-9])|(12[0-8]))$)" "$REABDIP" | sed 's/\//\\\//g' | sed  "s/^/add ipv6filter /" > $IPV6REAB
    grep -E "^(((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2}).){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2}))($|/(([1-9])|([1-2][0-9])|(3[0-2]))$)" "$REABDIP" | sed 's/\//\\\//g' | sed  "s/^/add ipv4filter /" > $IPV4REAB
    grep -vE  "^(.{2}--)|^(.*-.)|^(-)|^(#)|[äâëêïîöôüûàçèé&\!@,]|^$|.*blogspot\..*|^((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})\.){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})$" $REABDIP | grep -vE "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$" | awk '{ gsub("\\.+\\.",".");print }' > $DREAB
    if [ ! -f $DIR_DNS_BLACKLIST_ENABLED/ossi.conf ] ; then
    echo > $DIR_DNS_BLACKLIST_ENABLED/ossi.conf
    fi
    echo
    gettext 'Application whitelisting (restored area):'
    while read CATEGORIE
    do
    if [ "$(grep -c "$CATEGORIE" "$BL_CATEGORIES_AVAILABLE" )" -ge "1" ] ; then
        echo -n "."
        while read -r DOMAINE
        do
        cp -f $DIR_DNS_BLACKLIST_ENABLED/"$CATEGORIE".conf "$FILE_tmp"
        $SED "/$DOMAINE/d" "$FILE_tmp"
        cp -f "$FILE_tmp" $DIR_DNS_BLACKLIST_ENABLED/"$CATEGORIE".conf
        done < $DREAB
        
        while read -r IPV4
        do
        cp -f $DIR_IPV4_FILTER_ENABLED/"$CATEGORIE".conf "$FILE_tmp"
        $SED "/$IPV4/d" "$FILE_tmp"
        cp -f "$FILE_tmp" $DIR_IPV4_FILTER_ENABLED/"$CATEGORIE".conf
        done < $IPV4REAB
        
        while read -r IPV6
        do
        cp -f $DIR_IPV6_FILTER_ENABLED/"$CATEGORIE".conf "$FILE_tmp"
        $SED "/$IPV6/d" "$FILE_tmp"
        cp -f "$FILE_tmp" $DIR_IPV6_FILTER_ENABLED/"$CATEGORIE".conf
        done < $IPV6REAB
        for DOMAINE in $DOMAINEDEPOTS
        do
        cp -f $DIR_DNS_BLACKLIST_ENABLED/"$CATEGORIE".conf "$FILE_tmp"
        $SED "/$DOMAINE/d" "$FILE_tmp"
        cp -f "$FILE_tmp" $DIR_DNS_BLACKLIST_ENABLED/"$CATEGORIE".conf
        done
    fi
    done < $CATEGORIES_ENABLED
    {
    echo 'localhost
127.0.0.1'
    echo "$PRIVATE_IP4
$ADMIN_IP4
$BL_SERVER"
    for domain in $DOMAINEDEPOTS
    do
        echo "$domain"
    done
    grep -vE  "^(.{2}--)|^(.*-.)|^(-)|^(#)|[äâëêïîöôüûàçèé&\!@,]|^$|.*blogspot\..*|^((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})\.){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})$" $REABDIP | grep -vE "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$" | awk '{ gsub("\\.+\\.",".");print }' | sed -e"s/^\.//" | sed -e"s/^www.//"
    }  > "$E2GUXSITELIST"

     echo -n "."
     {
    echo "$BL_SERVER" | sed -e "s? ??" | sed -e "s?.*?server=/&/#?"
    for domain in $DOMAINEDEPOTS
    do
        echo "$domain" | sed -e "s? ??" | sed -e "s?.*?server=/&/#?"
    done

    }> "$DIR_DNS_WHITELIST_ENABLED"/whiteliste.depots.conf
    grep -vE  "^(.{2}--)|^(.*-.)|^(-)|^(#)|[äâëêïîöôüûàçèé&\!@,]|^$|.*blogspot\..*|^((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})\.){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})$" $REABDIP | grep -vE "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$" | awk '{ gsub("\\.+\\.",".");print }' | sed -e "s? ??" | sed -e "s?.*?server=/&/#?" >  "$DIR_DNS_WHITELIST_ENABLED"/whiteliste.ossi.conf
    echo
    $UMFILEtmp
    rm -f "$FILE_tmp"
    date +%H:%M:%S

    {
    ## on force à passer par forcesafesearch.google.com de
    ## manière transparente
    # retrieve forcesafesearch.google.com ip
    forcesafesearchgoogle=$(host -ta forcesafesearch.google.com|cut -d" " -f4)
    if [ "$( grep -c "^SAFEGOOGLE" $SAFE_CONF )" -eq 1 ];then
        echo "# forcesafesearch redirect server for google"
        # pour chaque sous domaine de google
        for subdomaingoogle in $(wget http://www.google.com/supported_domains -O - 2> /dev/null )
        do
        echo "address=/www$subdomaingoogle/$forcesafesearchgoogle"
        done
    fi
    if [ "$( grep -c "^SAFEYOUTUBE" $SAFE_CONF )" -eq 1 ];then
        echo "address=/www.youtube.com/$forcesafesearchgoogle"
    fi
    ## on force à passer par strict.bing.com de manière transparente
    if [ "$( grep -c "^SAFEBING" $SAFE_CONF )" -eq 1 ];then
        echo "address=/.bing.com/$(host -ta strict.bing.com |cut -d" " -f4 | grep -v alias | sed '1q;d')"
    fi

    if [ "$( grep -c "^SAFEDUCK" $SAFE_CONF )" -eq 1 ];then
        echo "# on force a passer par safe.duckduckgo.com"
        echo "address=/safe.duckduckgo.com/$(host -ta safe.duckduckgo.com|cut -d" " -f4 | grep -v alias | sed '1q;d')"
        ## les requêtes sur http(s)://duckduckgo.com sont
        ## redirigées vers lighttpd qui les renvoie vers
        ## safe.duckduckgo.com
        echo "address=/duckduckgo.com/$ADMIN_IP4"
    fi

    if [ "$( grep -c "^SAFEQWANT" $SAFE_CONF  )" -eq 1 ];then
        echo "# on force a passer par www.qwantjunior.com"
        echo "address=/www.qwantjunior.com/$(host -ta www.qwantjunior.com|cut -d" " -f4 | grep -v alias | sed '1q;d')"
        ## les requêtes sur http(s)://www.qwant.com sont
        ## redirigées vers lighttpd qui les renvoie vers
        ## www.qwantjunior.com
        echo "address=/www.qwant.com/$ADMIN_IP4"
    fi

    # pour les navigateurs qui ne prennent pas en compte
    # /etc/hosts comme google chrome
    echo "address=/admin.ct.local/$ADMIN_IP4"
    echo "address=/admin.ct.local/$ADMIN_IP6"
    echo "address=/privet.ct.local/$PRIVATE_IP4"
    echo "address=/privet.ct.local/$PRIVATE_IP6"
    } > $DIR_DNS_BLACKLIST_ENABLED/forcesafesearch.conf

     echo "</reabdomaine>"
}

function dnsmasqon() {
     echo "<dnsmasqon>"

     if [ "$(grep -c "$(sed -n "1 p" $CATEGORIES_ENABLED)" "$BL_CATEGORIES_AVAILABLE" )" -ge "1" ] ; then
    $SED "s?^DNSMASQ.*?DNSMASQ=BLACK?g" $FILE_CONF

    # on crée l'utilisateur dnsmasq si il n'existe pas déjà (comme
    # sous mageia par exemple). Pas utile sous debian et ubuntu,
    # car déjà fait par le deb
    if [ -z "$(id -u dnsmasq 2> /dev/null)" ]; then
       useradd --system -K PASS_MAX_DAYS=-1 --home /dev/null --no-create-home --comment "system user for dnsmasq" --shell /bin/false dnsmasq
       #adduser --system  --home /dev/null --comment "system user for dnsmasq" --no-create-home --shell /bin/false dnsmasq
    fi
    # on paramètre le service à se lancer avec l'utilisateur
    # dnsmasq. Pas utile sous debian et ubuntu, car déjà fait par
    # le deb
    if [ -f /etc/sysconfig/dnsmasq ] ; then
       $SED "s?^OPTIONS.*?OPTIONS= --user=dnsmasq?g" /etc/sysconfig/dnsmasq
    fi
    
    {
    echo '
# Configuration file for "dnsmasq with blackliste"
# Inclusion de la blacklist <domains> de Toulouse dans la configuration'
    echo "conf-dir=$DIR_DNS_BLACKLIST_ENABLED
listen-address=$PRIVATE_IP4
listen-address=$PRIVATE_IP6
port=54
no-dhcp-interface=lo
bind-interfaces
cache-size=1024
domain-needed
expand-hosts
bogus-priv
server=$DNS1v4
server=$DNS2v4
server=$DNS1v6
server=$DNS2v6
"
    } > $DNSMASQCONF

    # redémarre dnsmasq en prenant en compte la présence ou non de resolvconf.
    resolvconffixon
    $E2GUARDIANrestart
    $PROXYrestart
    else
    dnsmasqwhitelistonly
    fi
    echo "</dnsmasqon>"
}

function dnsmasqoff() {
    echo "<dnsmasqoff>"
    $SED "s?^DNSMASQ.*?DNSMASQ=OFF?" $FILE_CONF
    resolvconffixon
    $E2GUARDIANrestart
    $PROXYrestart
    echo "</dnsmasqoff>"
}

function ipglobal() {
    echo "<ipglobal>"
    ### BLOQUE TOUT PAR DEFAUT (si aucune règle n'est définie par la suite) ###
    $IPTABLES -P INPUT DROP
    $IPTABLES -P OUTPUT DROP
    $IPTABLES -P FORWARD DROP
    $IPTABLES6 -P INPUT DROP
    $IPTABLES6 -P OUTPUT DROP
    $IPTABLES6 -P FORWARD DROP
    # TCP Syn Flood
    $IPTABLES -A INPUT -p tcp --syn -m limit --limit 3/s -j ACCEPT
    $IPTABLES6 -A INPUT -p tcp --syn -m limit --limit 3/s -j ACCEPT
    # UDP Syn Flood
    $IPTABLES -A INPUT -p udp -m limit --limit 10/s -j ACCEPT
    $IPTABLES6 -A INPUT -p udp -m limit --limit 10/s -j ACCEPT
    ### IP indésirables
    echo "<$FILEIPBLACKLIST>"
    $IPTABLES -A OUTPUT -m set --match-set ipv4filterforall dst -j REJECT
    $IPTABLES6 -A OUTPUT -m set --match-set ipv6filterforall dst -j REJECT
    $IPTABLES -A INPUT -m set --match-set ipv4filterforall src -j DROP
    $IPTABLES6 -A INPUT -m set --match-set ipv6filterforall src -j DROP
    echo "</$FILEIPBLACKLIST>"


    ## autoriser le multicast dns (mDNS)
    $IPTABLES6 -A INPUT -p udp --sport 5353 -j ACCEPT
    $IPTABLES -A INPUT -p udp --sport 5353 -j ACCEPT
    $IPTABLES6 -A OUTPUT -p udp --dport 5353 -j ACCEPT
    $IPTABLES -A OUTPUT  -p udp --dport 5353 -j ACCEPT
    
    
    ## Link-Local Multicast Name Resolution (LLMNR) 
    $IPTABLES -A INPUT -p udp --dport 5355 -j ACCEPT
    $IPTABLES -A INPUT -p tcp --dport 5355 -j ACCEPT
    $IPTABLES6 -A INPUT -p udp --dport 5355 -j ACCEPT
    $IPTABLES6 -A INPUT -p tcp --dport 5355 -j ACCEPT
    $IPTABLES -A OUTPUT -p udp --dport 5355 -j ACCEPT
    $IPTABLES6 -A OUTPUT -p udp --dport 5355 -j ACCEPT
    $IPTABLES -A OUTPUT -p tcp --dport 5355 -j ACCEPT
    $IPTABLES6 -A OUTPUT -p tcp --dport 5355 -j ACCEPT
    
    
    ### ACCEPT ALL interface loopback ###
    $IPTABLES -A INPUT  -i lo -j ACCEPT
    $IPTABLES -A OUTPUT -o lo -j ACCEPT
    $IPTABLES6 -A INPUT  -i lo -j ACCEPT
    $IPTABLES6 -A OUTPUT -o lo -j ACCEPT

    ## accépter requette ipv6 de recherche de routeurs
    $IPTABLES6 -A OUTPUT -p icmpv6 -d ff02::2  -j ACCEPT
    $IPTABLES6 -A OUTPUT -p icmpv6 -d ff02::16  -j ACCEPT

    ### accepte en entrée les connexions déjà établies (en gros cela
    ### permet d'accepter les connexions initiées par son propre PC)
    $IPTABLES -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    $IPTABLES6 -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    ### DHCP
    $IPTABLES -A OUTPUT -p udp --sport 68 --dport 67 -j ACCEPT
    $IPTABLES -A INPUT -p udp --sport 67 --dport 68 -j ACCEPT
    $IPTABLES6 -A OUTPUT -p udp --sport 68 --dport 67 -j ACCEPT
    $IPTABLES6 -A INPUT -p udp --sport 67 --dport 68 -j ACCEPT

    ### DNS indispensable pour naviguer facilement sur le web ###
    $IPTABLES -A OUTPUT -p tcp -m tcp --dport 53 -j ACCEPT
    $IPTABLES -A OUTPUT -p udp -m udp --dport 53 -j ACCEPT
    $IPTABLES -A OUTPUT -d $PRIVATE_IP4 -p tcp -m tcp --dport 54 -j ACCEPT
    $IPTABLES -A OUTPUT -d $PRIVATE_IP4 -p udp -m udp --dport 54 -j ACCEPT
    $IPTABLES6 -A OUTPUT -p tcp -m tcp --dport 53 -j ACCEPT
    $IPTABLES6 -A OUTPUT -p udp -m udp --dport 53 -j ACCEPT
    $IPTABLES6 -A OUTPUT -d ::1 -p tcp -m tcp --dport 54 -j ACCEPT
    $IPTABLES6 -A OUTPUT -d ::1 -p udp -m udp --dport 54 -j ACCEPT

    ### HTTP navigation internet non sécurisée ###

    $IPTABLES -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
    $IPTABLES6 -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
    $IPTABLES -A OUTPUT -d 127.0.0.1 -p tcp -m tcp --dport $E2GUport -j ACCEPT
    $IPTABLES6 -A OUTPUT -d ::1 -p tcp -m tcp --dport $PROXYport -j ACCEPT

    ### HTTPS pour le site des banques .... ###
    $IPTABLES -A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT
    $IPTABLES6 -A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT

    ### ping ... autorise à "pinger" un ordinateur distant ###
    $IPTABLES -A OUTPUT -p icmp -j ACCEPT
    $IPTABLES6 -A OUTPUT -p icmpv6 -j ACCEPT

    ### clientNTP ... syncro à un serveur de temps ###
    $IPTABLES -A OUTPUT -p udp -m udp --dport 123 -j ACCEPT
    $IPTABLES6 -A OUTPUT -p udp -m udp --dport 123 -j ACCEPT

    # On autorise les requêtes FTP
    modprobe ip_conntrack_ftp
    $IPTABLES -A OUTPUT -p tcp --dport 21 -j ACCEPT
    $IPTABLES -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    $IPTABLES6 -A OUTPUT -p tcp --dport 21 -j ACCEPT
    $IPTABLES6 -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    
    # On autorise l'incmpv6 sur les liens locaux
    $IPTABLES6 -A INPUT -p icmpv6 -d fe80::/10  -j ACCEPT
    $IPTABLES6 -A INPUT -p icmpv6 -s fe80::/10  -j ACCEPT
    
    # An autorise le ssh en sortie vers les liens locaux (client)
    $IPTABLES6 -A OUTPUT -p tcp -d fe80::/10 --dport $PORTSSH -j ACCEPT
    if [ "$(grep -c "SRVSYNC=ON" "$DIR_CONF"/ctsync.conf)" -eq 1 ] ;then
    $IPTABLES6 -A INPUT -p tcp -s fe80::/10 --dport $PORTSSH -j ACCEPT
    fi
    
    echo "<$FILEFIRWALLCONF>"
    source "$FILEFIRWALLCONF"
    echo "</$FILEFIRWALLCONF>"

    ### LOG ### Log tout ce qui qui n'est pas accepté par une règle précédente
    $IPTABLES6 -A OUTPUT -j LOG  --log-prefix "ip6tables"
    $IPTABLES6 -A INPUT -j LOG   --log-prefix "ip6tables"
    $IPTABLES6 -A FORWARD -j LOG  --log-prefix "ip6tables"
    $IPTABLES -A OUTPUT -j LOG  --log-prefix "iptables"
    $IPTABLES -A INPUT -j LOG   --log-prefix "iptables"
    $IPTABLES -A FORWARD -j LOG  --log-prefix "iptables"

    if [ ! -e $RSYSLOGCTPARENTAL ] ;  then
    mkdir /var/log/iptables/
    echo > /var/log/iptables/iptables.log
    echo > /var/log/iptables/ip6tables.log
    {
    echo '
:msg,contains,"iptables" /var/log/iptables/iptables.log
&~

:msg,contains,"ip6tables" /var/log/iptables/ip6tables.log
&~

'
    } > $RSYSLOGCTPARENTAL
    $RSYSLOGRESTART
    fi
    if [ ! -e /etc/logrotate.d/iptables ] ; then
    {
    echo '
/var/log/iptables/*.log {
        daily
        missingok
        rotate 14
        compress
        delaycompress
        notifempty
        create 640 root adm
        sharedscripts
        postrotate
        service rsyslog restart ; sleep 5
        endscript
}
'
    } > /etc/logrotate.d/iptables
    fi
    echo "</ipglobal>"
}

function initfileiptables() {
    cat << EOF >  $FILEFIRWALLCONF
## on autorise tous le trafic sortant vers internet.
# \$IPTABLES -A OUTPUT -j ACCEPT
## on autorise tous le trafic sortant à destination de notre lan (PC imprimante de la maison)
\$IPTABLES -A OUTPUT -d \$reseau_box_ipv4 -j ACCEPT
## on acepte tous le trafic entrant en provenence de notre lan (PC imprimante de la maison)
\$IPTABLES -A INPUT -s \$reseau_box_ipv4 -j ACCEPT

### smtp + pop ssl thunderbird ...  ####
\$IPTABLES -A OUTPUT -p tcp -m tcp --dport 993 -j ACCEPT        # imap/ssl
\$IPTABLES -A OUTPUT -p tcp -m tcp --dport 995 -j ACCEPT        # pop/ssl
\$IPTABLES -A OUTPUT -p tcp -m tcp --dport 465 -j ACCEPT     # smtp/ssl

## Client Steam voir infos https://support.steampowered.com/kb_article.php?ref=8571-GLVN-8711&l=french
#\$IPTABLES -A OUTPUT -p udp -m udp --dport 27000:27015 -j ACCEPT          # (trafic pour le client jeu)
#\$IPTABLES -A OUTPUT -p udp -m udp --dport 27015:27030 -j ACCEPT          # (en général pour les matchs et HLTV)
#\$IPTABLES -A OUTPUT -p tcp -m tcp --dport 27014:27050 -j ACCEPT          # (pour les téléchargements sur Steam)
#\$IPTABLES -A INPUT  -s \$reseau_box_ipv4 -p udp -m multiport --sports 27031,27036 -j ACCEPT                 # (entrant, pour le Streaming local)
#\$IPTABLES -A INPUT  -s \$reseau_box_ipv4 -p tcp -m multiport --sports 27036,27037 -j ACCEPT                 # (entrant, pour le Streaming local)
#\$IPTABLES -A OUTPUT -p udp -m udp --dport 4380 -j ACCEPT             # chat audio Steam
## certains jeux nécessitent un accès direct sans proxy pour l'authentification https à ouvrir au cas par cas.
## exemple steam.goldenfrog.org
#\$IPTABLES -I OUTPUT -d 208.73.211.70 -m owner --uid-owner child1 -p tcp --dport 443 -j ACCEPT


## Serveurs dédiés ou Serveurs d'écoute
#\$IPTABLES -A INPUT  -p tcp --dport 27015 -j ACCEPT                     # (port Rcon SRCDS)

##Steamworks P2P et chat audio Steam
#\$IPTABLES -A OUTPUT -p udp -m udp --dport udp 3478 -j ACCEPT
#\$IPTABLES -A OUTPUT -p udp -m udp --dport udp 4379 -j ACCEPT
#\$IPTABLES -A OUTPUT -p udp -m udp --dport udp 4380 -j ACCEPT

## Steam Ports supplémentaires pour for Call of Duty: Modern Warfare 2 Multijoueur
#\$IPTABLES -A OUTPUT -p udp -m udp --dport udp 1500 -j ACCEPT
#\$IPTABLES -A OUTPUT -p udp -m udp --dport udp 3005 -j ACCEPT
#\$IPTABLES -A OUTPUT -p udp -m udp --dport udp 3101 -j ACCEPT
#\$IPTABLES -A OUTPUT -p udp -m udp --dport udp 28960 -j ACCEPT

# Ping Externe
# \$IPTABLES -A INPUT -i \$i_WAN_ipv4 -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT
# \$IPTABLES -A INPUT -i \$i_WAN_ipv4 -p icmp --icmp-type echo-reply -m limit --limit 1/s -j ACCEPT

### cups serveur , impriment partager sous cups
#\$IPTABLES -A OUTPUT -d \$ip_broadcast_ipv4 -p udp -m udp --sport 631 --dport 631 -j ACCEPT # diffusion des imprimantes partagées sur le réseau
#\$IPTABLES -A INPUT -s \$reseau_box_ipv4 -m state --state NEW -p TCP --dport 631 -j ACCEPT
#\$IPTABLES -I INPUT -s \$ipbox_ipv4 -m state --state NEW -p TCP --dport 631 -j DROP # drop les requêtes provenant de la passerelle

### emesene,pidgin,amsn...  ####
#\$IPTABLES -A OUTPUT -p tcp -m tcp --dport 1863 -j ACCEPT
#\$IPTABLES -A OUTPUT -p tcp -m tcp --dport 6891:6900 -j ACCEPT # pour transfert de fichiers , webcam
#\$IPTABLES -A OUTPUT -p udp -m udp --dport 6891:6900 -j ACCEPT # pour transfert de fichiers , webcam

###  smtp + pop thunderbird ...  ###
#\$IPTABLES -A OUTPUT -p tcp -m tcp --dport 25 -j ACCEPT
#\$IPTABLES -A OUTPUT -p tcp -m tcp --dport 110 -j ACCEPT
### client-transmission
# ouvre beaucoup de ports
#\$IPTABLES -A OUTPUT -p udp -m udp --sport 51413 --dport 1023:65535  -j ACCEPT
#\$IPTABLES -A OUTPUT -p tcp -m tcp --sport 30000:65535 --dport 1023:65535  -j ACCEPT
###Ryzom
#srvupdateRtzom=178.33.44.72
#srvRyzom1=176.31.229.93
#\$IPTABLES -A OUTPUT  -d \$srvupdateRtzom -p tcp --dport 873 -j ACCEPT
#\$IPTABLES -A OUTPUT  -d \$srvRyzom1 -p tcp --dport 43434 -j ACCEPT
#\$IPTABLES -A OUTPUT  -d \$srvRyzom1 -p tcp --dport 50000 -j ACCEPT
#\$IPTABLES -A OUTPUT  -d \$srvRyzom1 -p tcp --dport 40916 -j ACCEPT
#\$IPTABLES -A OUTPUT  -d \$srvRyzom1 -p udp --dport 47851:47860 -j ACCEPT
#\$IPTABLES -A OUTPUT  -d \$srvRyzom1 -p tcp --dport 47851:47860 -j ACCEPT
### Regnum Online
#\$IPTABLES -A OUTPUT  -d 91.123.197.131 -p tcp --dport 47300 -j ACCEPT # autentification
#\$IPTABLES -A OUTPUT  -d 91.123.197.142 -p tcp --dport 48000:48002  -j ACCEPT # nemon
### NeverWinter Nights 1
#\$IPTABLES -A OUTPUT  -p udp --dport 5120:5121 -j ACCEPT
#\$IPTABLES -I OUTPUT  -d 204.50.199.9 -j DROP # nwmaster.bioware.com permet d'éviter le temps d'attente avant l'ouverture du multijoueur " >>  $FILEIPTABLES
### LandesEternelles
#\$IPTABLES -A OUTPUT  -d 62.93.225.45 -p tcp --dport 3000 -j ACCEPT
### Batel for Wesnoth
#14998 pour version stable.
#14999 pour version stable précédente.
#15000 pour version de développement.
#15001 télécharger addons
#\$IPTABLES -A OUTPUT  -d 65.18.193.12 -p tcp --sport 1023:65535 --dport 14998:15001 -j ACCEPT
#\$IPTABLES -A INPUT   -p tcp --sport 1023:65535 --dport 15000 -j ACCEPT
EOF
    chown root:root  $FILEFIRWALLCONF
    chmod 750  $FILEFIRWALLCONF

}

function iptablesreload() {
    echo "<iptablesreload>"
    if [ ! -f $FILEIPTIMEWEB ]; then 
    touch $FILEIPTIMEWEB
    chown root:root  $FILEIPTIMEWEB
    chmod 750  $FILEIPTIMEWEB
    fi
    if [ ! -f $FILEIPBLACKLIST ]; then 
    {
    echo '# enter here the addresses to be filtered for all the system, including root and privileged accounts.
# - one ip per line.
# - ipv4 address or subnet ipv4 / mask (ip/xxx.xxx.xxx.xxx or ip/1 to 32)
# - ipv6 address or subnet ipv6 / mask (ip/ 1 to 128)
# examples:
# 10.10.2.3
# 192.168.182.0/24
# 2001:db8::f23f
# 2001:db8::/44'
    } >  $FILEIPBLACKLIST
    chown root:root  $FILEIPBLACKLIST
    chmod 750  $FILEIPBLACKLIST
    
    fi
    if [ ! -f $FILEFIRWALLCONF ]; then 
    initfileiptables
    fi
    # on force la regénération des règles du parfeu sauf si c'est un une tache planifiée.
    if [ $arg1 != "-cron" ];then
        md5iptold="-old"
    else
        md5iptold=$(grep MD5IPT= "$FILE_CONF" | cut -d"=" -f2)
    fi
    md5iptnew="$({
md5sum ${FILEIPBLACKLIST} ${FILEFIRWALLCONF} ${FILEIPTIMEWEB} ${FILE_GCTOFFCONF}
listeusers
md5sum ${DIR_IPV4_FILTER_ENABLED}/*
md5sum ${DIR_IPV6_FILTER_ENABLED}/*
grep -c IPRULES=ON $FILE_CONF
echo "$FILTRAGEISOFF"
} | md5sum )"
    #echo "$md5iptold = $md5iptnew"
    # on regénère les règles que si ce n'est pas une tache planifier ou si une changement dans la conf système à eu lieux entre 2 taches. 
    if [ ! "$md5iptold" = "$md5iptnew" ]; then
        ### SUPPRESSION de TOUTES LES ANCIENNES TABLES (OUVRE TOUT!!) ###
        $IPTABLES6 -F
        $IPTABLES6 -X
        $IPTABLES6 -t nat -F
        $IPTABLES6 -t mangle -F
        $IPTABLES6 -t nat -X
        $IPTABLES6 -t nat -N ctparental
        $IPTABLES6 -P INPUT ACCEPT
        $IPTABLES6 -P OUTPUT ACCEPT
        $IPTABLES6 -P FORWARD ACCEPT
        $IPTABLES -F
        $IPTABLES -X
        $IPTABLES -t nat -F
        $IPTABLES -t mangle -F
        $IPTABLES -t nat -X
        $IPTABLES -t nat -N ctparental
        $IPTABLES -P INPUT ACCEPT
        $IPTABLES -P OUTPUT ACCEPT
        $IPTABLES -P FORWARD ACCEPT
        $IPSET flush
        $IPSET destroy 

        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
        $IPTABLES -t nat -A OUTPUT -j ctparental
        $IPTABLES6 -t nat -A OUTPUT -j ctparental
        # création des blacklist ipset ipv4 et ipv6  
        ipv4filter_set_length=$(wc -l ${DIR_IPV4_FILTER_ENABLED}/* | awk '{print $1}' | tail -n 1)
        ipv6filter_set_length=$(wc -l ${DIR_IPV6_FILTER_ENABLED}/* | awk '{print $1}' | tail -n 1)
        echo "create ipv4filter hash:net family inet hashsize 1024 maxelem $ipv4filter_set_length" > $DIR_CONF/ipsetipv4filter
        echo "create ipv6filter hash:net family inet6 hashsize 1024 maxelem $ipv6filter_set_length" > $DIR_CONF/ipsetipv6filter
        cat ${DIR_IPV4_FILTER_ENABLED}/* | sort -u >> $DIR_CONF/ipsetipv4filter
        cat ${DIR_IPV6_FILTER_ENABLED}/* | sort -u >> $DIR_CONF/ipsetipv6filter
        $IPSET restore -file $DIR_CONF/ipsetipv4filter
        $IPSET restore -file $DIR_CONF/ipsetipv6filter
        # création des blacklist ipset ipv4 et ipv6 pour tous le systeme y compris pour root active uniquement après un CTparental -ipton. 
        grep -E "^(((2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2}).){3}(2[0-5][0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2}))($|/(([1-9])|([1-2][0-9])|(3[0-2]))$)" ${FILEIPBLACKLIST} | sort -u | sed  "s/^/add ipv4filterforall /" > /tmp/ipv4filterforall
        grep -E "^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))($|/(([1-9])|([1-9][0-9])|(1[0-1][0-9])|(12[0-8]))$)" ${FILEIPBLACKLIST} | sort -u | sed  "s/^/add ipv6filterforall /" > /tmp/ipv6filterforall
        ipv4filterforall_set_length=$(wc -l /tmp/ipv4filterforall | awk '{print $1}' | tail -n 1)
        ipv6filterforall_set_length=$(wc -l /tmp/ipv6filterforall | awk '{print $1}' | tail -n 1)
        echo "create ipv4filterforall hash:net family inet hashsize 1024 maxelem $ipv4filterforall_set_length" > $DIR_CONF/ipsetipv4filterforall
        echo "create ipv6filterforall hash:net family inet6 hashsize 1024 maxelem $ipv6filterforall_set_length" > $DIR_CONF/ipsetipv6filterforall
        cat /tmp/ipv4filterforall >> $DIR_CONF/ipsetipv4filterforall
        cat /tmp/ipv4filterforall >> $DIR_CONF/ipsetipv6filterforall
        $IPSET restore -file $DIR_CONF/ipsetipv4filterforall
        $IPSET restore -file $DIR_CONF/ipsetipv6filterforall
        # Force privoxy à utiliser dnsmasq sur le port 54 en ipv6 et en ipv4
        $IPTABLES -t nat -A ctparental -m owner --uid-owner "$PROXYuser" -p udp --dport 53 -j DNAT --to $PRIVATE_IP4:54
        $IPTABLES6 -t nat -A ctparental -m owner --uid-owner "$PROXYuser" -p udp --dport 53 -j DNAT --to [$PRIVATE_IP6]:54
        $IPTABLES -t nat -A ctparental -m owner --uid-owner "$PROXYuser" -p tcp --dport 53 -j DNAT --to $PRIVATE_IP4:54
        $IPTABLES6 -t nat -A ctparental -m owner --uid-owner "$PROXYuser" -p tcp --dport 53 -j DNAT --to [$PRIVATE_IP6]:54
        ## on rejet les ip fournie par la blackliste de toulouse
        $IPTABLES -A OUTPUT -m set --match-set ipv4filter dst -m owner --uid-owner "$PROXYuser" -j REJECT
        $IPTABLES6 -A OUTPUT -m set --match-set ipv6filter dst -m owner --uid-owner "$PROXYuser" -j REJECT
        #for user in $(listeusers) ; do
        listeusers | while read -r user
        do
            if  [ "$(groups "$user" | grep -c -E "( ctoff$)|( ctoff )|( root$)|( root )" )" -eq 0 ];then
            ## on rejet les ip fournie par la blackliste de toulouse
            $IPTABLES -A OUTPUT -m set --match-set ipv4filter dst -m owner --uid-owner "$user" -j REJECT
            $IPTABLES6 -A OUTPUT -m set --match-set ipv6filter dst -m owner --uid-owner "$user" -j REJECT
            #on redirige les requêtes DNS ipv4 des usagers filtrés sur dnsmasq très important pour l'https.
            $IPTABLES -t nat -A ctparental -m owner --uid-owner "$user" -p tcp --dport 53 -j DNAT --to $PRIVATE_IP4:54
            $IPTABLES -t nat -A ctparental -m owner --uid-owner "$user" -p udp --dport 53 -j DNAT --to $PRIVATE_IP4:54
            #on redirige les requêtes DNS ipv6 des usagers filtrés sur dnsmasq très important pour l'https.
            $IPTABLES6 -t nat -A ctparental -m owner --uid-owner "$user" -p tcp --dport 53 -j DNAT --to [$PRIVATE_IP6]:54
            $IPTABLES6 -t nat -A ctparental -m owner --uid-owner "$user" -p udp --dport 53 -j DNAT --to [$PRIVATE_IP6]:54
            #force passage par dansguardian pour les utilisateurs filtrés
            $IPTABLES -t nat -A ctparental ! -d 127.0.0.1/8 -m owner --uid-owner "$user" -p tcp --dport 80 -j DNAT --to 127.0.0.1:"$E2GUport"
            $IPTABLES -t nat -A ctparental ! -d 127.0.0.1/8 -m owner --uid-owner "$user" -p tcp --dport "$PROXYport" -j DNAT --to 127.0.0.1:"$E2GUport"
            # e2guardian ne gérant pas encore ipv6 on se contente de privoxy + dnsmasq on force donc le passage par privoxy pour le http.
            $IPTABLES6 -t nat -A ctparental -d 2000::/3 -m owner --uid-owner "$user" -p tcp --dport 80 -j DNAT --to [::1]:"$PROXYport"
           fi
        done
           echo "<$FILEIPTIMEWEB>"
           source "$FILEIPTIMEWEB"
           echo "</$FILEIPTIMEWEB>"

        if [ "$( grep -c IPRULES=ON $FILE_CONF )" -eq 1 ];then
           ipglobal
        fi

        
        fi

        # Save configuration so that it survives a reboot
        $IPTABLESsave > "$IPTABLESsaveFILE"
        $IPTABLES6save > "$IPTABLES6saveFILE"
        if [ -e "$DIRHTML"/cactparental.crt ];then
        updatecauser
        fi
    $SED "s?^MD5IPT.*?MD5IPT=$md5iptnew?" $FILE_CONF
    fi
    echo "</iptablesreload>"
}

function updatecauser() {
    echo "<updatecauser>"
    #for user in $(listeusers) ; do
    listeusers | while read -r user
    do
    HOMEPCUSER=$(getent passwd "$user" | cut -d ':' -f6)
    #on installe le cacertificat dans tous les profils firefox
    if [ -d "$HOMEPCUSER/.mozilla/firefox" ] ;then
    #for cert8db in $(find $HOMEPCUSER/.mozilla/firefox/ -mindepth 2 -maxdepth 2 -name "cert8.db")
    find "$HOMEPCUSER/.mozilla/firefox/" -mindepth 2 -maxdepth 2 -name "cert8.db" | while read -r cert8db
    do
        cert8dbdir="$(dirname "${cert8db}")"
        # on supprime tous les anciens certificats
        while true
        do
        certutil -D -d "$cert8dbdir"/ -n"CActparental - ctparental" > /dev/null 2>&1
        if [ ! $? -eq 0 ];then
            break
        fi
        done
        # on ajoute le nouveau certificat
        certutil -A -d "$cert8dbdir"/ -i "$DIRHTML"/cactparental.crt -n"CActparental - ctparental" -t "CT,c,c"
        chown ${user}:${user} ${cert8db} > /dev/null 2>&1
        chown ${user}:${user} ${cert8dbdir}/key3.db > /dev/null 2>&1
        chown ${user}:${user} ${cert8dbdir}/pkcs11.txt > /dev/null 2>&1
    done
    #for cert9db in $(find $HOMEPCUSER/.mozilla/firefox/ -mindepth 2 -maxdepth 2 -name "cert9.db")
    find $HOMEPCUSER/.mozilla/firefox/ -mindepth 2 -maxdepth 2 -name "cert9.db" | while read -r cert9db
    do
        cert9dbdir=$(dirname ${cert9db});
        # on supprime tous les anciens certificats
        while true
        do
        certutil -D -d sql:"$cert9dbdir"/ -n"CActparental - ctparental" > /dev/null 2>&1
        if [ ! $? -eq 0 ];then
            break
        fi
        done
        certutil -A -d sql:"$cert9dbdir"/ -i "$DIRHTML"/cactparental.crt -n"CActparental - ctparental" -t "CT,c,c"
        chown ${user}:${user} ${cert9db} > /dev/null 2>&1
        chown ${user}:${user} ${cert9dbdir}/key4.db > /dev/null 2>&1
        chown ${user}:${user} ${cert9dbdir}/pkcs11.txt > /dev/null 2>&1
    done
    fi
    #on install le cacertificat dans tous les profile chrome chromium
    if [ -f "$HOMEPCUSER/.pki/nssdb/cert9.db" ] ;then
        cert9dbdir="$HOMEPCUSER/.pki/nssdb/"
        # on supprime tous les anciens certificats
        while true
        do
        certutil -D -d sql:"$cert9dbdir"/ -n"CActparental - ctparental" > /dev/null 2>&1
        if [ ! $? -eq 0 ];then
            break
        fi
        done
        certutil -A -d sql:"$cert9dbdir"/ -i "$DIRHTML"/cactparental.crt -n"CActparental - ctparental" -t "CT,c,c"
        chown ${user}:${user} ${cert9db} > /dev/null 2>&1
        chown ${user}:${user} ${cert9dbdir}/key4.db > /dev/null 2>&1
        chown ${user}:${user} ${cert9dbdir}/pkcs11.txt > /dev/null 2>&1
    fi
    done
     echo "</updatecauser>"
}

function dnsmasqwhitelistonly() {
    $SED "s?^DNSMASQ.*?DNSMASQ=WHITE?" $FILE_CONF
    {
    echo '
# Configuration file for "dnsmasq with whiteliste"
# Inclusion de la whiteliste <domains> de Toulouse dans la configuration'
    echo "conf-dir=$DIR_DNS_WHITELIST_ENABLED
listen-address=$PRIVATE_IP4
listen-address=$PRIVATE_IP6
port=54
no-dhcp-interface=lo
bind-interfaces
cache-size=1024
domain-needed
expand-hosts
bogus-priv
server=$DNS1v4
server=$DNS2v4
server=$DNS1v6
server=$DNS2v6
address=/localhost/127.0.0.1
address=/localhost/::1
address=/#/$PRIVATE_IP4 #redirige vers $PRIVATE_IP4 pour tout ce qui n'a pas été résolu dans les listes blanches
address=/#/$PRIVATE_IP6 #redirige vers $PRIVATE_IP6 pour tout ce qui n'a pas été résolu dans les listes blanches
"
    } > $DNSMASQCONF

    $DNSMASQrestart
    $E2GUARDIANrestart
    $PROXYrestart
}

function FoncHTTPDCONF() {
    echo "<FoncHTTPDCONF>"
    $SRVHTTPstop
    rm -rf "${DIRHTML:?}"/*
    mkdir "$DIRHTML" 2> /dev/null
    mkdir -p "$DIRadminHTML"
    mkdir -p "$DIRHTML"
    if [ ! -z "$DIRhtmlPersonaliser" ];then
        cp -rf "$DIRhtmlPersonaliser"/* "$DIRHTML"
    else
        cp -rf "$DIR_SHARE"/www/CTparental/* "$DIRHTML"
    fi
    cp -rf "$DIR_SHARE"/www/CTadmin/* "$DIRadminHTML"

    chmod 644 "$FILE_CONF"
    chown root:"$GROUPHTTPD" "$FILE_CONF"

    if [ $nomanuel -eq 0 ]||[ "$arg1" = "-uhtml" ]; then
        configloginpassword
    else
        ## variables récupérees par héritage du script DEBIAN/postinst
        debconfloginhttp=${debconfloginhttp:="admin"}
        debconfpassword=${debconfpassword:="admin"}
        addadminhttpdapr1md5php "$debconfloginhttp" "$debconfpassword"
        unset debconfpassword
        unset debconfloginhttp
    fi
    source "$DIR_SHARE/confhttp"
    if [ -e "$DIRHTML/index.php" ] ;  then
        ln -s "$DIRHTML"/index.php "$DIRHTML"/err404.php
    else
        if [ -e "$DIRHTML/index.html" ] ;  then
            ln -s  "$DIRHTML"/index.html "$DIRHTML"/err404.html
        fi
        $SED "s?^server.error-handler-404 =.*?server.error-handler-404 =\"err404.html\"?g" "$CTPARENTALCONFHTTPD"
    fi

    #chown root:"$GROUPHTTPD" "$IPREAB"
    #chmod 664 "$IPREAB"
    chown root:"$GROUPHTTPD" "$REABDIP"
    chmod 664 "$REABDIP"
    chown root:"$GROUPHTTPD" "$BL_DIPOSSI"
    chmod 664 "$BL_DIPOSSI"
    chown root:"$GROUPHTTPD" "$CATEGORIES_ENABLED"
    chmod 664 "$CATEGORIES_ENABLED"
    chown root:"$GROUPHTTPD" "$SAFE_CONF"
    chmod 664 "$SAFE_CONF"
    chmod 660 /etc/sudoers
    chown root:"$GROUPHTTPD" "${DIRE2G}lists/bannedextensionlist"
    chmod 664 "${DIRE2G}lists/bannedextensionlist"
    chown root:"$GROUPHTTPD" "${DIRE2G}lists/bannedmimetypelist"
    chmod 664 "${DIRE2G}lists/bannedmimetypelist"
    chown root:"$GROUPHTTPD" "${DIRE2G}lists/bannedsitelist"
    chmod 664 "${DIRE2G}lists/bannedsitelist"

    if [ "$(grep -c Defaults:"$USERHTTPD" /etc/sudoers )" -ge "1" ] ; then
    $SED "/^Defaults:$USERHTTPD/d" /etc/sudoers
    fi
    echo "Defaults:$USERHTTPD !requiretty" >> /etc/sudoers

    if [ "$(grep -c "^$USERHTTPD " /etc/sudoers )" -ge "1" ] ; then
    $SED "/^$USERHTTPD /d" /etc/sudoers
    fi
    echo "$USERHTTPD localhost=(root) NOPASSWD:/usr/bin/CTparental *" >> /etc/sudoers

    unset sudotest
    chmod 440 /etc/sudoers
    if [ ! -f $FILE_HCONF ] ; then
        echo > $FILE_HCONF
    fi
    chown root:"$GROUPHTTPD" "$FILE_HCONF"
    chmod 664 "$FILE_HCONF"
    if [ -f "$FILE_GCTOFFCONF" ] ; then
        chown root:"$GROUPHTTPD" "$FILE_GCTOFFCONF"
        chmod 664 "$FILE_GCTOFFCONF"
    fi

    if [ ! -f "$FILE_HCOMPT" ] ; then
        echo "date=$(date +%D)" > "$FILE_HCOMPT"
    fi
    chown root:"$GROUPHTTPD" "$FILE_HCOMPT"
    chmod 664 "$FILE_HCOMPT"

    chown -R root:"$GROUPHTTPD" "$DIRHTML"
    chown -R root:"$GROUPHTTPD" "$DIRadminHTML"
    CActparental
    $SRVHTTPstart
    test=$?
    if [ ! $test -eq 0 ];then
        gettext 'Error launching of lighttpd service'
        set -e
        exit 1
    fi
    echo "</FoncHTTPDCONF>"
}

function configloginpassword() {
     while true
     do
    loginhttp=$(whiptail --title "$(gettext 'Login')" --nocancel --inputbox "$(gettext 'Enter login to the administration interface')
$(gettext '    - Only letters or numbers.')
$(gettext '    - 5 characters minimum:')" 10 60 3>&1 1>&2 2>&3)
    loginhttp="$(echo "$loginhttp" | grep -E "^([a-zA-Z0-9])*$")"
    if [ "${#loginhttp}" -ge 5  ];then
        break
    fi
     done
     while true
     do
    password=$(whiptail --title "$(gettext 'Password')" --nocancel --passwordbox "$(gettext 'Enter your password and press OK to continue.')" 10 60 3>&1 1>&2 2>&3)
    password2=$(whiptail --title "$(gettext 'Password')" --nocancel --passwordbox "$(gettext 'Confirm your password and press OK to continue.')" 10 60 3>&1 1>&2 2>&3)
    if [ "$password" = "$password2" ] ; then
        password="$(echo "$password" | grep -E "^([a-z0-9A-Z]|[&éè~#{}()ç_@à?.;:/\!,\$<>=£\%\])*$")"
        if [ "${#password}" -ge 8 ] ; then
        break
        else
        whiptail --title "$(gettext "Password")" --msgbox "$(gettext "Password is not complex enough, it must contain at least:")
$(gettext "- 8 characters total, 1 uppercase, lowercase 1, number 1")
$(gettext "and one special character among the following") &éè~#{}()ç_@à?.;:/!,$<>=£% " 14 60
        fi
    else
        whiptail --title "$(gettext "Password")" --msgbox "$(gettext "The password entered is not identical to the first.")" 14 60
    fi
     done
    addadminhttpdapr1md5php "$loginhttp" "$password"

}

function CActparental() {
     echo "<CActparental>"
     DIR_TMP=${TMPDIR-/tmp}/ctparental-mkcert.$$
     mkdir "$DIR_TMP"
     mkdir "$CADIR" 2> /dev/null

     ## création de la clef privée ca et du certificat ca
     openssl genrsa  2048 > "$DIR_TMP"/cactparental.key 2> /dev/null
     openssl req -new -x509 -sha256 -subj "/C=FR/ST=FRANCE/L=ici/O=ctparental/CN=CActparental" -days 5000 -key "$DIR_TMP"/cactparental.key > "$DIR_TMP"/cactparental.crt

     ## création clef et certificat *.ct.local et signature par le ca
     openssl genrsa 2048 > "$DIR_TMP"/ct.local.key 2> /dev/null
     openssl req -new -sha256  -subj "/C=FR/ST=FRANCE/L=ici/O=ctparental/CN=*.ct.local" -key "$DIR_TMP"/ct.local.key > "$DIR_TMP"/ct.local.csr
     openssl x509 -req -extfile <(printf "subjectAltName=DNS:admin.ct.local,DNS:privet.ct.local") -in "$DIR_TMP"/ct.local.csr -days 5000 -out "$DIR_TMP"/ct.local.crt -CA "$DIR_TMP"/cactparental.crt -CAkey "$DIR_TMP"/cactparental.key -CAcreateserial -CAserial "$DIR_TMP"/ca.srl

     ## création du certificat duckduckgo pour redirection vers safe.duckduckgo.com
     openssl genrsa 2048 > "$DIR_TMP"/duckduckgo.key 2> /dev/null
     openssl req -new -sha256 -subj "/C=FR/ST=FRANCE/L=ici/O=ctparental/CN=duckduckgo.com" -key "$DIR_TMP"/duckduckgo.key > "$DIR_TMP"/duckduckgo.csr
     openssl x509 -req  -extfile <(printf "subjectAltName=DNS:duckduckgo.com,DNS:www.duckduckgo.com") -in "$DIR_TMP"/duckduckgo.csr -days 5000 -out "$DIR_TMP"/duckduckgo.crt -CA "$DIR_TMP"/cactparental.crt -CAkey "$DIR_TMP"/cactparental.key -CAserial "$DIR_TMP"/ca.srl

     ## création du certificat www.qwant.com pour redirection vers www.qwantjunior.com
     openssl genrsa 2048 > "$DIR_TMP"/qwant.key 2> /dev/null
     openssl req -new -sha256 -subj "/C=FR/ST=FRANCE/L=ici/O=ctparental/CN=www.qwant.com" -key "$DIR_TMP"/qwant.key > "$DIR_TMP"/qwant.csr
     openssl x509 -req -extfile <(printf "subjectAltName=DNS:www.qwant.com,DNS:qwant.com") -in "$DIR_TMP"/qwant.csr -days 5000 -out "$DIR_TMP"/qwant.crt -CA "$DIR_TMP"/cactparental.crt -CAkey "$DIR_TMP"/cactparental.key -CAserial "$DIR_TMP"/ca.srl

    ## instalation de la CA dans les ca de confiance.
    cp -f "$DIR_TMP"/cactparental.crt "$CADIR"/
    cp -f "$DIR_TMP"/cactparental.crt "$DIRHTML"
    cp -f "$DIR_TMP"/cactparental.crt "$REPCAMOZ" 2> /dev/null
    ## instalation des certificats serveur
    cat "$DIR_TMP"/ct.local.key "$DIR_TMP"/ct.local.crt > "$PEMSRVDIR"/ct.local.pem
    cat "$DIR_TMP"/duckduckgo.key "$DIR_TMP"/duckduckgo.crt > "$PEMSRVDIR"/duckduckgo.pem
    cat "$DIR_TMP"/qwant.key "$DIR_TMP"/qwant.crt > "$PEMSRVDIR"/qwant.pem
    rm -rf "$DIR_TMP"
    $UPDATECASYSTEM
    updatecauser
    echo "</CActparental>"
}

function install() {
    # on empaiche la réinstall manuel par dessus une install par paquet.
    if [ $nomanuel -eq 0 ]; then
    muninstall=$(gettext "Install by package was detected, please use this command to uninstall ctparental.")
    if [ "$(dpkg -l ctparental | grep -c ^i)" -eq 1 ] ;then
        echo "$muninstall"
        echo "$CMDREMOVE ctparental"
        exit 0
    fi
    if [ "$(rpm -q -a | grep -c ctparental )" -eq 1 ] ;then
        echo "$muninstall"
        echo "$CMDREMOVE ctparental"
        exit 0
    fi
    fi
    echo > ${DIR_IPV4_FILTER_ENABLED}/ossi.conf
    echo > ${DIR_IPV6_FILTER_ENABLED}/ossi.conf
    $DISABLESSH
    $SSHstop
    {
    echo "$ADMIN_IP4 admin.ct.local "
    echo "$ADMIN_IP6 admin.ct.local "
    echo "$PRIVATE_IP4 privet.ct.local "
    echo "$PRIVATE_IP6 privet.ct.local "
    } >> /etc/hosts
    # on réactive l'ipv6 si besoin.
    if [ -f $FILESYSCTL ] ; then
        if [ "$( grep -c "net.ipv6.conf.all.disable_ipv6=" "$FILESYSCTL" )" -ge "1" ] ; then
        $SED "s?^net.ipv6.conf.all.disable_ipv6=.*?net.ipv6.conf.all.disable_ipv6=0?" "$FILESYSCTL"
        fi
        if [ "$( grep -c "net.ipv6.conf.default.disable_ipv6=" "$FILESYSCTL" )" -ge "1" ] ; then
        $SED "s?^net.ipv6.conf.default.disable_ipv6=.*?net.ipv6.conf.default.disable_ipv6=0?" "$FILESYSCTL"
        fi
        if [ "$( grep -c "net.ipv6.conf.lo.disable_ipv6=" "$FILESYSCTL" )" -ge "1" ] ; then
        $SED "s?^net.ipv6.conf.lo.disable_ipv6=.*?net.ipv6.conf.lo.disable_ipv6=0?" "$FILESYSCTL"
        fi
        if [ "$( grep -c "net.ipv4.ip_forward=" "$FILESYSCTL" )" -ge "1" ] ; then
        $SED "s?^#net.ipv4.ip_forward=.*?net.ipv4.ip_forward=1?" "$FILESYSCTL"
        $SED "s?^net.ipv4.ip_forward=.*?net.ipv4.ip_forward=1?" "$FILESYSCTL"
        else
        echo 'net.ipv4.ip_forward=1' >> "$FILESYSCTL"
        fi
        if [ "$( grep -c "net.ipv6.conf.default.forwarding=" "$FILESYSCTL" )" -ge "1" ] ; then
        $SED "s?^#net.ipv6.conf.default.forwarding=.*?net.ipv6.conf.default.forwarding=1?" "$FILESYSCTL"
        $SED "s?^net.ipv6.conf.default.forwarding=.*?net.ipv6.conf.default.forwarding=1?" "$FILESYSCTL"
        else
        echo 'net.ipv6.conf.default.forwarding=1' >> "$FILESYSCTL"
        fi
        if [ "$( grep -c "net.ipv6.conf.all.forwarding=" "$FILESYSCTL" )" -ge "1" ] ; then
        $SED "s?^#net.ipv6.conf.all.forwarding=.*?net.ipv6.conf.all.forwarding=1?" "$FILESYSCTL"
        $SED "s?^net.ipv6.conf.all.forwarding=.*?net.ipv6.conf.all.forwarding=1?" "$FILESYSCTL"
        else
        echo 'net.ipv6.conf.all.forwarding=1' >> "$FILESYSCTL"
        fi
        sysctl -p "$FILESYSCTL"
    fi
    
    ######################
    FILTRAGEISOFF=1
# on configure les ip pour l'interface ctparental et la page d'interception.
if [ $(systemctl list-unit-files | grep -c systemd-networkd) -ge 1 ] ; then
	systemctl enable systemd-networkd   
    {
	echo "[Match]
Name=lo
[Network]
Address=$PRIVATE_IP6/128
Address=$ADMIN_IP6/128
"
	} > /etc/systemd/network/ctparentallo.network
    systemctl restart systemd-networkd
else
if [ ! -f /etc/systemd/system/loctparental.service ];then
    ip addr add $PRIVATE_IP6/128 dev lo label lo:1 
    ip addr add $ADMIN_IP6/128  dev lo label lo:2

    {
    echo "#!/bin/bash
ip addr add $PRIVATE_IP6/128 dev lo label lo:1
ip addr add $ADMIN_IP6/128 dev lo label lo:2

"
    } > /usr/bin/CTlo
    chmod +x /usr/bin/CTlo

    {
    echo '[Unit]
Description=admin.ct.local and privet.ct.local ipv6 loopback
Wants=network.target
After=network-pre.target dbus.service
Before=network.target 

[Service]
ExecStart=/usr/bin/CTlo
Type=simple

[Install]
WantedBy=default.target

'
    } > /etc/systemd/system/loctparental.service
    chmod 664 /etc/systemd/system/loctparental.service
    systemctl daemon-reload
    systemctl enable loctparental
fi 
fi

    
    if [ $nomanuel -eq 0 ]; then
    cp -rf www "$DIR_SHARE"
    cp -rf confe2guardian "$DIR_SHARE"
    cp -f locale/fr/LC_MESSAGES/ctparental.mo        /usr/share/locale/fr/LC_MESSAGES/
    cp -f locale/es/LC_MESSAGES/ctparental.mo        /usr/share/locale/es/LC_MESSAGES/
    fi
    iptablesreload
    groupadd ctoff

    if [ $nomanuel -eq 0 ]; then
    vim -h > /dev/null 2>&1
    if [ $? -eq 0 ] ; then
       EDIT="vim "
    fi
    nano -h > /dev/null 2>&1
    if [ $? -eq 0 ] ; then
       EDIT=${EDIT:="nano "}
    fi
    vi -h > /dev/null 2>&1
    if [ $? -eq 0 ] ; then
       EDIT=${EDIT:="vi "}
    fi

    if [ -f gpl-3.0.fr.txt ] ; then
       cp -f gpl-3.0.fr.txt "$DIR_SHARE"/
    fi
    if [ -f gpl-3.0.txt ] ; then
       cp -f gpl-3.0.txt "$DIR_SHARE"/
    fi
    if [ -f CHANGELOG ] ; then
       cp -f CHANGELOG "$DIR_SHARE"/
    fi
    if [ -f dist.conf ];then
       cp -f dist.conf "$DIR_SHARE"/dist.conf.orig
       cp -f dist.conf $DIR_CONF/
    fi
    while true; do
       $EDIT $DIR_CONF/dist.conf
       clear
       grep -v -E ^# "$DIR_CONF"/dist.conf | grep -v ^$
       gettext 'Enter: S to continue with these parameters.'
       gettext 'Enter: Q to Quit setup.'
       gettext 'Enter any other choice to change settings.'
       read choi
       case $choi in
        S | s )
           break
           ;;
        Q | q )
           exit
           ;;
       esac
    done

    fi
    if [ -f $DIR_CONF/dist.conf ];then
    source  $DIR_CONF/dist.conf
    fi

    if [ -f /etc/NetworkManager/NetworkManager.conf ];then
    $SED "s/^dns=dnsmasq/#dns=dnsmasq/g" /etc/NetworkManager/NetworkManager.conf
    $NWMANAGERrestart
    sleep 5
    fi

    mkdir $tempDIR
    mkdir -p $DIR_CONF
    if [ ! -f $CATEGORIES_ENABLED ];then
    initblenabled
    fi
    cat /etc/resolv.conf > $DIR_CONF/resolv.conf.sav
    if [ $noinstalldep -eq 0 ]; then
    for PACKAGECT in $CONFLICTS
    do
       cmd="${CMDREMOVE} ${PACKAGECT}"
       $cmd 2> /dev/null
    done
    fi
    if [ $noinstalldep -eq 0 ]; then
    cmd="${CMDINSTALL} ${DEPENDANCES}"
    $cmd
    fi
    iptdisableconflict
    if [ ! -f blacklists.tar.gz ]
    then
    download
    else
    tar -xzf blacklists.tar.gz -C $tempDIR
    if [ ! $? -eq 0 ]; then
            gettext 'archive extraction error , process interrupted'
            uninstall
            set -e
            exit 1
    fi
    rm -rf ${DIR_DNS_FILTER_AVAILABLE:?}/
    mkdir $DIR_DNS_FILTER_AVAILABLE
    fi
    adapt
    catChoice
    dnsmasqon
    $SED "s?^LASTUPDATE.*?LASTUPDATE=$THISDAYS=$(date +%d-%m-%Y\ %T)?g" $FILE_CONF
    confe2guardian
    confproxy
    FoncHTTPDCONF
    activegourpectoff
    FILTRAGEISOFF=0
    rm -f /etc/rsyslog.d/iptables.conf # for old install
    rm -f $RSYSLOGCTPARENTAL
    $RSYSLOGRESTART
    $SED "s?^MD5IPT.*?MD5IPT=0?" $FILE_CONF
    iptablesreload
    $ENHTTP
    $ENDNSMASQ
    $ENNWMANAGER
    $ENIPTABLESSAVE
    $ENE2GUARDIAN
    $ENPROXY
    $ENNETWORK
    {
     echo "[Unit]
Description=CTparental avery minutes
After=network-online.target


[Service]
User=root
WorkingDirectory=/root/
ExecStart=$CHEMINCTPARENTLE -cron
Type=oneshot

[Install]
WantedBy=default.target

"
    } > /etc/systemd/system/CTparentalcron.service
    {
     echo "
[Unit]
Description=ipset persistent configuration
#
DefaultDependencies=no
Before=network.target

# ipset sets should be loaded before iptables
# Because creating iptables rules with names of non-existent sets is not possible
Before=CTparentalfirewall.service

ConditionFileNotEmpty=$DIR_CONF/ipsetipv4filter
ConditionFileNotEmpty=$DIR_CONF/ipsetipv6filter
ConditionFileNotEmpty=$DIR_CONF/ipsetipv4filterforall
ConditionFileNotEmpty=$DIR_CONF/ipsetipv6filterforall

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=$IPSET restore -file $DIR_CONF/ipsetipv4filter 
ExecStart=$IPSET restore -file $DIR_CONF/ipsetipv6filter
ExecStart=$IPSET restore -file $DIR_CONF/ipsetipv4filterforall
ExecStart=$IPSET restore -file $DIR_CONF/ipsetipv6filterforall
ExecStop=$IPSET flush
ExecStopPost=$IPSET destroy

[Install]
WantedBy=multi-user.target

RequiredBy=CTparentalfirewall.service
"
} > /etc/systemd/system/CTparentalipset.service
    chmod 664 /etc/systemd/system/CTparentalipset.service

# ajout du service de persistance des iptables.
{
echo "#!/bin/bash
$IPTABLESrestore < $IPTABLESsaveFILE
$IPTABLES6restore < $IPTABLES6saveFILE
"
} > /usr/sbin/CTiptablesrestore
chown root:root /usr/sbin/CTiptablesrestore
chmod 550 /usr/sbin/CTiptablesrestore
{
    echo "[Unit]
Description=iptables load one boot
Wants=network.target
After=network-online.target

ConditionFileNotEmpty=$IPTABLESsaveFILE
ConditionFileNotEmpty=$IPTABLES6saveFILE

[Service]
ExecStart=/usr/sbin/CTiptablesrestore
Type=simple

[Install]
WantedBy=default.target

"
    } > /etc/systemd/system/CTparentalfirewall.service
    chmod 664 /etc/systemd/system/CTparentalfirewall.service


# on redémare le démon systemd pour prendre en compte ce nouveau service
systemctl daemon-reload
systemctl enable CTparentalipset.service
systemctl enable CTparentalfirewall.service
    {
    echo "
[Unit]
Description=updates parental control from the blacklist of the University of Toulouse every week

[Timer]
# on attent 2 minute après le boot
OnBootSec=2min
# toute les minutes aprés le dernier lancement
OnUnitActiveSec=1min
[Install]
WantedBy=timers.target
"
    } > /etc/systemd/system/CTparentalcron.timer
    systemctl enable CTparentalcron.timer
    systemctl start CTparentalcron.timer
    echo > "$DIR_CONF"/ctsync.conf
}

function nomade() {
    echo "<nomade>"
    #### si il y a un changement dans la conf réseaux ####
    if [ "$DNS1v4" != "$( grep DNS1v4 $FILE_CONF | cut -d"=" -f2 )" ] || \
    [ "$DNS2v4" != "$( grep DNS2v4 $FILE_CONF | cut -d"=" -f2 )" ] || \
    [ "$DNS1v6" != "$( grep DNS1v6 $FILE_CONF | cut -d"=" -f2 )" ] || \
    [ "$DNS2v6" != "$( grep DNS2v6 $FILE_CONF | cut -d"=" -f2 )" ] || \
    [ "$i_WAN_ipv4" != "$( grep I_WAN_IPV4 $FILE_CONF | cut -d"=" -f2 )" ] || \
    [ "$i_WAN_ipv6" != "$( grep I_WAN_IPV6 $FILE_CONF | cut -d"=" -f2 )" ] || \
    [ "$ipbox_ipv4" != "$( grep IP_BOX_IPV4 $FILE_CONF | cut -d"=" -f2 )" ] || \
    [ "$ipbox_ipv6" != "$( grep IP_BOX_IPV6 $FILE_CONF | cut -d"=" -f2 )" ] || \
    [ "$ip_i_WAN_ipv4" != "$( grep IP_IWAN_IPV4 $FILE_CONF | cut -d"=" -f2 )" ] || \
    [ "$ip_i_WAN_ipv6" != "$( grep IP_IWAN_IPV6 $FILE_CONF | cut -d"=" -f2 )" ]
    then
    networkisoknext
    # on sauvegarde ces changement dans le fichier de conf CTparental.
    $SED "/^I_WAN_IPV4=/d" "$FILE_CONF"
    $SED "/^I_WAN_IPV6=/d" "$FILE_CONF"
    $SED "/^IP_BOX_IPV4=/d" "$FILE_CONF"
    $SED "/^IP_BOX_IPV6=/d" "$FILE_CONF"
    $SED "/^IP_IWAN_IPV4=/d" "$FILE_CONF"
    $SED "/^IP_IWAN_IPV6=/d" "$FILE_CONF"
    $SED "/^DNS1v4=/d" "$FILE_CONF"
    $SED "/^DNS2v4=/d" "$FILE_CONF"
    $SED "/^DNS1v6=/d" "$FILE_CONF"
    $SED "/^DNS2v6=/d" "$FILE_CONF"
    { echo I_WAN_IPV4="$i_WAN_ipv4"
     echo IP_BOX_IPV4="$ipbox_ipv4"
     echo IP_BOX_IPV6="$ipbox_ipv6"
     echo IP_IWAN_IPV4="$ip_i_WAN_ipv4"
     echo IP_IWAN_IPV6="$ip_i_WAN_ipv6"
     echo I_WAN_IPV6="$i_WAN_ipv6"
     echo DNS1v4="$DNS1v4"
     echo DNS2v4="$DNS2v4"
     echo DNS1v6="$DNS1v6"
     echo DNS2v6="$DNS2v6"
    } >> $FILE_CONF
    # on modifie la conf dnsmasq
    dnsmasqon
    # on reconfigure les règles du pare-feu.
    iptablesreload
     fi
    echo "</nomade>"
}

function updatelistgctoff() {
    if [ ! -f $FILE_GCTOFFCONF ] ; then
    echo -n > $FILE_GCTOFFCONF
    chown root:"$GROUPHTTPD" "$FILE_GCTOFFCONF"
    chmod 664 "$FILE_GCTOFFCONF"
    fi
    $MFILEtmp
    cp -f "$FILE_GCTOFFCONF" "$FILE_tmp"
    #for PCUSER in $(listeusers)
    listeusers | while read -r PCUSER
    do
        ## on ajoute tous les utilisateurs manquants dans la liste
        if [ "$(cat < $FILE_tmp | sed -e "s/^-//" | sed -e "s/^+//" | sed -e "s/^#//" | grep -c -E "^$PCUSER$")" -eq 0 ];then
            if [ "$(groups "$PCUSER" | grep -c -E "( root$)|( root )|( sudo$)|( sudo )")" -eq 1 ];then
            #si l'utilisateur fait partie d'un groupe d'administration de la machine on l'ajoute sans filtrage par défaut.
            echo "+$PCUSER" >> $FILE_tmp
            else
            #si non avec filtrage  par défaut.
            echo "#$PCUSER" >> $FILE_tmp
            fi
        fi
        ## on adapte les ligne en cas de changement ajout/suppression d'un group d'administration.
        if [ "$(groups "$PCUSER" | grep -c -E "( root$)|( root )|( sudo$)|( sudo )")" -eq 1 ];then
            $SED "s/^#${PCUSER}$/-$PCUSER/" "$FILE_tmp"
            $SED "s/^$${PCUSER}$/+$PCUSER/" "$FILE_tmp"
        else
            $SED "s/^+${PCUSER}$/$PCUSER/" "$FILE_tmp"
            $SED "s/^-${PCUSER}$/#$PCUSER/" "$FILE_tmp"
        fi
    done
    ## on supprimes les lignes vide du fichier.
    $SED '/^$/d' "$FILE_tmp"
    ## on supprime tout ceux qui n'existent plus sur le pc.
    while read line
    do
    PCUSER=$(echo $line | sed -e "s/^-//" | sed -e "s/^+//" | sed -e "s/^#//" )
    groups $PCUSER > /dev/null
    if [ $? -eq 1 ];then
        $SED "/^$${PCUSER}$/d" "$FILE_tmp"
        $SED "/^#${PCUSER}$/d" "$FILE_tmp"
        $SED "/^+${PCUSER}$/d" "$FILE_tmp"
        $SED "/^-${PCUSER}$/d" "$FILE_tmp"
    fi
    if [ ! -d "$(getent passwd $PCUSER | cut -d":" -f6)" ]; then
        $SED "/^$${PCUSER}$/d" "$FILE_tmp"
        $SED "/^#${PCUSER}$/d" "$FILE_tmp"
        $SED "/^+${PCUSER}$/d" "$FILE_tmp"
        $SED "/^-${PCUSER}$/d" "$FILE_tmp"
    fi
    done < $FILE_tmp
    if [ "$(md5sum $FILE_tmp | awk '{print $1}')" = "$(md5sum $FILE_GCTOFFCONF | awk '{print $1}')" ];then
        echo "0"
    else
        echo "1"
        cp -f "$FILE_tmp" "$FILE_GCTOFFCONF"
    fi
    rm -f $FILE_tmp
    $UMFILEtmp
}

function applistegctoff() {
    echo "<applistegctoff>"
    $ADDUSERTOGROUP root ctoff 2> /dev/null
    while read line
    do
        PCUSER=$(echo $line | sed -e "s/^-//" | sed -e "s/^+//" | sed -e "s/^#//" )
        if [ "$(echo "$line" | grep -c "#")" -eq 1 ];then
            $DELUSERTOGROUP "$PCUSER" ctoff 2> /dev/null
        else
            if [ "$(echo "$line" | grep -c "^-")" -eq 1 ];then
                $DELUSERTOGROUP "$PCUSER" ctoff 2> /dev/null
            else
                $ADDUSERTOGROUP "$PCUSER" ctoff 2> /dev/null
            fi
        fi
     done < "$FILE_GCTOFFCONF"
     $SED "s?^MD5IPT.*?MD5IPT=-old?" $FILE_CONF
     echo "</applistegctoff>"
}

function activegourpectoff() {
     echo "<activegourpectoff>"
     groupadd ctoff
     $SED "s?^GCTOFF.*?GCTOFF=ON?" $FILE_CONF
     updatelistgctoff
     applistegctoff
     chown root:"$GROUPHTTPD" "$FILE_GCTOFFCONF"
     chmod 660 "$FILE_GCTOFFCONF"
     
     echo "</activegourpectoff>"
}

function desactivegourpectoff() {
     groupdel ctoff 2> /dev/null
     $SED "s?^GCTOFF.*?GCTOFF=OFF?g" $FILE_CONF
}

function uninstall() {
     # On force la désinstall par dpkg ou rpm si l'install a été effectuée par un package.
     if [ $nomanuel -eq 0 ]; then
        muninstall=$(gettext "Install by package was detected, please use this command to uninstall ctparental.")
        if [ "$(dpkg -l ctparental | grep -c ^i)" -eq 1 ] ;then
            echo "$muninstall"
            echo "$CMDREMOVE ctparental"
            exit 0
        fi
        if [ "$(rpm -q -a | grep -c ctparental )" -eq 1 ] ;then
            echo "$muninstall"
            echo "$CMDREMOVE ctparental"
            exit 0
        fi
     fi
     $SED "/.ct.local/d" /etc/hosts
    if [ -f "$DIR_CONF"/ctsync.conf ];then
        if [ "$( grep -c "SRVSYNC=ON" "$DIR_CONF"/ctsync.conf )" -eq 1 ];then
            serversyncoff
        fi
        if [ "$(grep -c "CSYNC=ON" "$DIR_CONF"/ctsync.conf)" -eq 1 ] ;then
            clientsyncoff
        fi
    fi
    systemctl disable CTparentalfirewall
    systemctl daemon-reload
    rm -f /etc/systemd/system/CTparentalfirewall.service
    if [ -f /etc/systemd/system/loctparental.service ] ;then
        systemctl disable loctparental #for old install
        systemctl daemon-reload #for old install
        rm -f /etc/systemd/network/ctparentallo.network
        systemctl disable systemd-networkd  
        rm -f /etc/systemd/system/loctparental.service #for old install
        rm -f /usr/bin/CTlo #for old install
        ip addr delete $PRIVATE_IP6/128 dev lo 2> /dev/null
        ip addr delete $ADMIN_IP6/128 dev lo 2> /dev/null
    else #for old install
        if [ -f /etc/sysconfig/network-scripts/ifcfg-lo1 ] ;then #for old install
            rm -f /etc/sysconfig/network-scripts/ifcfg-lo1 #for old install
        fi #for old install
        if [ -f /etc/sysconfig/network-scripts/ifcfg-lo2 ] ;then #for old install
            rm -f /etc/sysconfig/network-scripts/ifcfg-lo2 #for old install
        fi #for old install
        if [ -f /etc/network/interfaces.d/ctparentallo ];then #for old install
            rm -f /etc/network/interfaces.d/ctparentallo #for old install
        fi #for old install
        $NETWORKINGrestart #for old install
    fi
     $SED "s?.*IPRULES=.*?IPRULES=OFF?g" $FILE_CONF
     rm -f "$FILEFIRWALLCONF"
     rm -f "$FILEIPBLACKLIST"
     rm -f "$FILEIPTIMEWEB"
     rm -f $RSYSLOGCTPARENTAL
     rm -f /usr/sbin/CTiptablesrestore
     $RSYSLOGRESTART
     desactivegourpectoff
     autoupdateoff
     dnsmasqoff
     resolvconffixoff
     FILTRAGEISOFF=1
     iptablesreload
     $SRVHTTPstop
     $DNSMASQstop
     if [ $nomanuel -eq 1 ]; then
    # en install par le deb on n'efface pas les fichiers installés par celui-ci
    #for unite in $( systemctl list-unit-files | grep CTparental | awk '{print $1}' )
    systemctl list-unit-files | grep CTparental | awk '{print $1}' | while read -r unite
    do
    systemctl stop $unite
    systemctl disable $unite
    done
    rm -f /etc/systemd/system/CTparental*
    systemctl daemon-reload
    rm -rf "$DIRHTML"
    cd "$DIR_CONF"
    for file in *
    do
        if [ ! "$(echo "$file" | grep -c -E ".*.conf")" -ge 1 ] ;then
        rm -rf ${DIR_CONF:?}/"$file"
        fi
    done
     else
    rm -rf "$DIRadminHTML"
    rm -rf "$DIRHTML"
    rm -rf "$DIR_SHARE"
    rm -rf "$DIR_CONF"
     fi

     rm -rf "$tempDIR"
     rm -rf /usr/share/lighttpd/*
     rm -f "$CTPARENTALCONFHTTPD"
     if [ -f /etc/NetworkManager/NetworkManager.conf ];then
    $SED "s/^#dns=dnsmasq/dns=dnsmasq/" /etc/NetworkManager/NetworkManager.conf
    $NWMANAGERrestart
      sleep 5
     fi

     if [ $noinstalldep -eq 0 ]; then
    for PACKAGECT in $DEPENDANCES
    do
        $CMDREMOVE "$PACKAGECT" 2> /dev/null
    done
     fi

     # désactivation du module ip_conntrack_ftp
     if [ $(grep -c ip_conntrack_ftp "$FILEMODULESLOAD" ) -ge 1 ] ; then
    $SED "s?.*ip_conntrack_ftp.*?#ip_conntrack_ftp?g" "$FILEMODULESLOAD"
     else
    echo "#ip_conntrack_ftp" >> "$FILEMODULESLOAD"
     fi
     modprobe -r ip_conntrack_ftp
     $SED "s?.*ip_conntrack_ftp.*?#ip_conntrack_ftp?g" "$FILEMODULESLOAD"

     rm -f "$PEMSRVDIR"/ct.local.pem
     rm -f "$PEMSRVDIR"/duckduckgo.pem
     rm -f "$PEMSRVDIR"/qwant.pem
     rm -f "$CADIR"/cactparental.crt
     rm -f "$DIRHTML"/cactparental.crt
     rm -f "$REPCAMOZ"/cactparental.crt
     $UPDATECASYSTEM
     #for user in $(listeusers) ; do
     listeusers | while read -r user
     do
    HOMEPCUSER=$(getent passwd "$user" | cut -d ':' -f6)
    #for cert8db in $(find $HOMEPCUSER/ -name "cert8.db"  | grep -v Trash )
    find $HOMEPCUSER/ -name "cert8.db"  | grep -v Trash | while read -r cert8db
    do
        cert8dbdir=$(dirname ${cert8db});
        # on supprime tous les anciens certificats
        while true
        do
        certutil -D -d "$cert8dbdir"/ -n"CActparental - ctparental" > /dev/null 2>&1
        if [ ! $? -eq 0 ];then
            break
        fi
        done
    done
    #for cert9db in $(find $HOMEPCUSER/ -name "cert9.db" | grep -v Trash)
    find $HOMEPCUSER/ -name "cert9.db" | grep -v Trash | while read -r cert9db
    do
            cert9dbdir=$(dirname ${cert9db});
        # on supprime tous les anciens certificats
        while true
        do
        certutil -D -d sql:"$cert9dbdir"/ -n"CActparental - ctparental" > /dev/null 2>&1
        if [ ! $? -eq 0 ];then
            break
        fi
        done
    done
     done
     #unsetproxy
     # on réouvre l'ipv6
     $IPTABLES6 -F
     $IPTABLES6 -X
     $IPTABLES6 -t nat -F
     $IPTABLES6 -t nat -X
     $IPTABLES6 -P INPUT ACCEPT
     $IPTABLES6 -P OUTPUT ACCEPT
     $IPTABLES6 -P FORWARD ACCEPT
     rm -f "$DIR_CONF"/ctsync.conf
     userdel ctdigtest
}

function choiblenabled() {
     echo -n > $CATEGORIES_ENABLED
     clear
     gettext 'Do you want to filter by Blacklist or Whitelist B/W:'
     while true; do
         read choiBW
         case $choiBW in
             B | b )
        cat_av="$BL_CATEGORIES_AVAILABLE"
        break
        ;;
        W | w )
        cat_av="$WL_CATEGORIES_AVAILABLE"
        break
        ;;
    esac
     done

     cat  < $cat_av | while read CATEGORIE
     do
    clear
    gettext 'Choice of filtered categories to apply.'
    echo ""
    eval_gettext "Do you want to enable this category \$CATEGORIE  O/N:"
    (
        while true ; do
        unset choi
        read choi
        case $choi in
            O | o )
            echo "OUI"
            echo "$CATEGORIE" >> "$CATEGORIES_ENABLED"
            break
            ;;
            N | n )
            break
            ;;
        esac
        done
    ) < /dev/tty
     done
}

function errortime1() {
     clear
     at=$(gettext "at")
     and=$(gettext "and")
     h=$(gettext ":")
     or=$(gettext "or")
     echo -e "$(gettext "The start time must be strictly less than the end time:")$RougeD$input$Fcolor "
     echo "exemple: 00${h}00 $at 23${h}59 $or 08${h}00 $at 12${h}00 $and 14${h}00 $at 16${h}50"
     echo -e -n "$RougeD$PCUSER$Fcolor $(gettext "is allowed to connect the") $BleuD${DAYS[$NumDAY]}$Fcolor $(gettext "at:")"
}

function errortime2() {
     clear
     at=$(gettext "at")
     and=$(gettext "and")
     h=$(gettext ":")
     or=$(gettext "or")
     echo -e "$(gettext "Bad syntax:")$RougeD$input$Fcolor "
     echo "exemple: 00${h}00 $at 23${h}59 $or 08${h}00 $at 12${h}00 $and 14${h}00 $at 16${h}50"
     echo -e -n "$RougeD$PCUSER$Fcolor $(gettext "is allowed to connect the") $BleuD${DAYS[$NumDAY]}$Fcolor $(gettext "at:")"
}

function updatetimelogin() {
if [ ! -f $FILEIPTIMEWEB ]; then 
    touch $FILEIPTIMEWEB
fi
#USERSCONECT=$(who | awk '//{print $1}' | sort -u)
if [ "$( grep -c "$(date +%D)" $FILE_HCOMPT )" -eq 1 ] ; then
    # on incrémente le compteur de temps de connection. Pour
    # chaque utilisateur connecté
    #for PCUSER in $USERSCONECT
    who | awk '//{print $1}' | sort -u | while read -r PCUSER
    do
        if [ "$( grep -c "^$PCUSER=user=" $FILE_HCONF )" -eq 1 ] ;then
            if [ "$( grep -c "^$PCUSER=" $FILE_HCOMPT )" -eq 0 ] ;then
                    echo "$PCUSER=1=1" >> $FILE_HCOMPT
            else
                var=$(($( grep "^$PCUSER=" $FILE_HCOMPT | cut -d"=" -f2 ) + 1 ))
                uidpcuser=$(id -u $PCUSER)
                if [ "$(ss -t -e -o state established | grep -c uid:$uidpcuser)" -ge 1 ];then
                    varweb=$(($( grep "^$PCUSER=" $FILE_HCOMPT | cut -d"=" -f3 ) + 1 ))
                else
                    varweb=$( grep "^$PCUSER=" $FILE_HCOMPT | cut -d"=" -f3)
                fi
                $SED "s?^$PCUSER=.*?$PCUSER=$var=$varweb?g" $FILE_HCOMPT
                count=$(($( grep "^$PCUSER=user=" $FILE_HCONF | cut -d "=" -f3 ) - var ))
                countweb=$(($( grep "^$PCUSER=user=" $FILE_HCONF | cut -d "=" -f4 ) - varweb ))
                # si le compteur de l'usager dépasse la valeur max
                # autorisée on verrouille le compte et on
                # déconnecte l'utilisateur.
                if [ $count -le 0 ];then
                    /usr/bin/skill -KILL -u"$PCUSER"
                    passwd -l "$PCUSER"
                fi

                if [ "$countweb" -le 0 ];then
                    if [ "$( grep -c "$PCUSER" $FILEIPTIMEWEB )" -eq 0 ];then
                        # on bloque l'accès direct , via dansguardian et via le proxy
                        echo "$IPTABLES -A OUTPUT ! -d 127.0.0.1/8 -m owner --uid-owner $PCUSER -j REJECT" >> "$FILEIPTIMEWEB"
                        echo "$IPTABLES -A OUTPUT -d 127.0.0.1/8 -m owner --uid-owner $PCUSER -p tcp --dport $E2GUport -j REJECT" >> "$FILEIPTIMEWEB"
                        echo "$IPTABLES -A OUTPUT -d 127.0.0.1/8 -m owner --uid-owner $PCUSER -p tcp --dport $PROXYport -j REJECT" >> "$FILEIPTIMEWEB"
                        iptablesreload
                    fi
                else
                    if [ "$( grep -c "$PCUSER" $FILEIPTIMEWEB )" -ge 1 ];then
                        $SED "/$PCUSER/d" $FILEIPTIMEWEB
                        iptablesreload
                    fi
                fi
            fi
        else
            # on efface les lignes relatives à cet utilisateur
            if [ "$( grep -c "$PCUSER" $FILEIPTIMEWEB )" -ge 1 ];then
                $SED "/$PCUSER/d" $FILEIPTIMEWEB
                iptablesreload
            fi
            $SED "/^$PCUSER=/d" $FILE_HCOMPT
        fi
    done
else
     # on réactive tous les comptes
     #for PCUSER in $(listeusers)
     listeusers | while read -r PCUSER
     do
         passwd -u "$PCUSER"
     done
     # on remet tous les compteurs à zéro.
     echo "date=$(date +%D)" > $FILE_HCOMPT
     echo > $FILEIPTIMEWEB
     iptablesreload
fi
}

function requiredpamtime() {
     TESTGESTIONNAIRE=0
     if [ ! -f $DIRPAM$COMMONFILEGS ] ; then
    for FILE in $GESTIONNAIREDESESSIONS
    do
        if [ -f "$DIRPAM""$FILE" ];then
        if [ "$( grep -c "^account required pam_time.so" "$DIRPAM$FILE" )" -eq 0  ] ; then
            $SED "1i account required pam_time.so"  "$DIRPAM$FILE"
        fi
        TESTGESTIONNAIRE=1
        fi
    done
    if [ $TESTGESTIONNAIRE -eq 0 ] ; then
        gettext 'No known session manager has been detected.'
        gettext 'so it is impossible to activate the time control connections'
        desactivetimelogin
        exit 1
    fi
     else
    if [ "$( grep -c "^account required pam_time.so" "$DIRPAM$COMMONFILEGS")" -eq 0  ] ; then
        $SED "1i account required pam_time.so"  $DIRPAM$COMMONFILEGS
    fi
     fi

     if [ ! -f $FILEPAMTIMECONF.old ] ; then
    cp $FILEPAMTIMECONF $FILEPAMTIMECONF.old
     fi
     echo "*;*;root;Al0000-2400" > $FILEPAMTIMECONF
}

function activetimelogin() {
    requiredpamtime

    #for PCUSER in $(listeusers)
    listeusers | while read -r PCUSER
    do
    HOMEPCUSER=$(getent passwd "$PCUSER" | cut -d ':' -f6)
    $SED "/^$PCUSER=/d" $FILE_HCONF
    eval_gettext "\$PCUSER is allowed to connect 7/7 24/24 O/N?"
    choi=""
    while true; do
        read choi
            case $choi in
        O | o )
            alltime="O"
            echo "$PCUSER=admin=" >> $FILE_HCONF
               break
            ;;
        N| n )
            alltime="N"
            clear
            eval_gettext "\$PCUSER is allowed to connect X minutes per day
X (1 a 1440) = "
            while true; do
            read choi
            if [ "$choi" -ge 1 ];then
                if [ "$choi" -le 1440 ];then
                timesession=$choi
                break
                fi
            fi
            gettext "X must take a value between 1 and 1440
"
            done
            clear
            eval_gettext "\$PCUSER is allowed to surf the Internet X minutes per day
X ( 1 a \$timesession )= "
            while true; do
            read choi
            if [ "$choi" -ge 1 ];then
                if [ "$choi" -le "$timesession" ];then
                timeweb=$choi
                break
                fi
            fi
            eval_gettext "X must take a value between 1 and $timesession
"
            done
            echo "$PCUSER=user=$timesession=$timeweb" >> $FILE_HCONF
            break
            ;;
        esac
    done

    for NumDAY in 0 1 2 3 4 5 6
    do
        if [ $alltime = "O" ];then
        break
        fi

            clear
            at=$(gettext "at")
            and=$(gettext "and")
            h=$(gettext ":")
            or=$(gettext "or")
            echo "exemple: 00${h}00 $at 23${h}59 $or 08${h}00 $at 12${h}00 $and 14${h}00 $at 16${h}50"
            echo -e -n "$RougeD$PCUSER$Fcolor $(gettext "is allowed to connect the") $BleuD${DAYS[$NumDAY]}$Fcolor $(gettext "at:")"
            while true; do
        read choi
        input=$choi
        # mise en forme de la variable choi pour pam
        choi=$(echo "$choi" | sed -e "s/$h//g" | sed -e "s/ //g" | sed -e "s/$at/-/g" | sed -e "s/$and/:/g" )
        if [ "$( echo "$choi" | grep -E -c "^([0-1][0-9]|2[0-3])[0-5][0-9]-([0-1][0-9]|2[0-3])[0-5][0-9]$|^([0-1][0-9]|2[0-3])[0-5][0-9]-([0-1][0-9]|2[0-3])[0-5][0-9]:([0-1][0-9]|2[0-3])[0-5][0-9]-([0-1][0-9]|2[0-3])[0-5][0-9]$" )" -eq 1 ];then
                    int1=$(echo "$choi" | cut -d ":" -f1 | cut -d "-" -f1)
                    int2=$(echo "$choi" | cut -d ":" -f1 | cut -d "-" -f2)
                    int3=$(echo "$choi" | cut -d ":" -f2 | cut -d "-" -f1)
                    int4=$(echo "$choi" | cut -d ":" -f2 | cut -d "-" -f2)
                    if [ "$int1" -lt "$int2" ];then
            if [ ! "$(echo "$choi" | grep -E -c ":")" -eq 1 ] ; then
                            if [ "$NumDAY" -eq 6 ] ; then
                HORAIRESPAM="$HORAIRESPAM${DAYSPAM[$NumDAY]}$int1-$int2"
                            else
                HORAIRESPAM="$HORAIRESPAM${DAYSPAM[$NumDAY]}$int1-$int2|"
                            fi
                            m1=${int1:2:4}
                            h1=${int1:0:2}
                            m2=${int2:2:4}
                            h2=${int2:0:2}
                echo "$PCUSER=$NumDAY=$h1${h}h$m1:$h2${h}h$m2" >> "$FILE_HCONF"
                break
            else
                            if [ "$int2" -lt "$int3" ];then
                if [ "$int3" -lt "$int4" ];then
                    if [ "$NumDAY" -eq 6 ] ; then
                    HORAIRESPAM="$HORAIRESPAM${DAYSPAM[$NumDAY]}$int1-$int2|${DAYSPAM[$NumDAY]}$int3-$int4"
                    else
                    HORAIRESPAM="$HORAIRESPAM${DAYSPAM[$NumDAY]}$int1-$int2|${DAYSPAM[$NumDAY]}$int3-$int4|"
                    fi
                    m1=${int1:2:4}
                    h1=${int1:0:2}
                    m2=${int2:2:4}
                    h2=${int2:0:2}
                    m3=${int3:2:4}
                    h3=${int3:0:2}
                    m4=${int4:2:4}
                    h4=${int4:0:2}
                    ## minutes heures jourdumois mois jourdelasemaine utilisateur  commande
                    echo "$PCUSER=$NumDAY=$h1${h}h$m1:$h2${h}h$m2:$h3${h}h$m3:$h4${h}h$m4" >> "$FILE_HCONF"
                    break
                else
                    errortime1
                fi
                            else
                errortime1
                            fi
            fi
                    else
            errortime1
                    fi
        else
                    errortime2
        fi
            done
        done
     done
    echo >> $FILE_HCONF
    $SED "s?^HOURSCONNECT.*?HOURSCONNECT=ON?" $FILE_CONF
    readTimeFILECONF
}

function desactivetimelogin() {
    echo "<desactivetimelogin>"
    for FILE in $GESTIONNAIREDESESSIONS
    do
    $SED "/account required pam_time.so/d" "$DIRPAM""$FILE" 2> /dev/null
    done
    $SED "/account required pam_time.so/d" "$DIRPAM""$COMMONFILEGS" 2> /dev/null

    cat $FILEPAMTIMECONF.old > $FILEPAMTIMECONF
    #for unite in $( systemctl list-unit-files | grep CTparentalskill | awk '{print $1}' )
    systemctl list-unit-files | grep CTparentalskill | awk '{print $1}' | while read -r unite
    do
    systemctl stop $unite
    systemctl disable $unite
    done
    #for unite in $( systemctl list-unit-files | grep CTparentalnotify | awk '{print $1}' )
    systemctl list-unit-files | grep CTparentalnotify | awk '{print $1}' | while read -r unite
    do
    systemctl stop $unite
    systemctl disable $unite
    done
    rm -f /etc/systemd/system/CTparentalnotify*
    systemctl daemon-reload
    $SED "s?^HOURSCONNECT.*?HOURSCONNECT=OFF?" $FILE_CONF
    #for PCUSER in $(listeusers)
    listeusers | while read -r PCUSER
    do
    passwd -u "$PCUSER" > /dev/null
    done
    # on remet tous les compteurs à zéro.
    echo "date=$(date +%D)" > $FILE_HCOMPT
    echo > $FILE_HCONF
    echo > $FILEIPTIMEWEB
    iptablesreload
    echo "</desactivetimelogin>"
}

source "$DIR_SHARE/listeusers"

function readTimeFILECONF() {
    requiredpamtime
   ## on créer le service instancifier pout fermer les session utilisateurs
   ## plus d'info ici https://access.redhat.com/documentation/fr-fr/red_hat_enterprise_linux/7/html/system_administrators_guide/sect-managing_services_with_systemd-unit_files
    {
     echo '[Unit]
Description=fermeture de la session de %I
After=network-online.target

[Service]
User=root
WorkingDirectory=/root/
ExecStart=/usr/bin/skill -KILL -u%i
Type=oneshot

[Install]
WantedBy=default.target

'
} > "/etc/systemd/system/CTparentalskill@.service"

    {
     echo '[Unit]
Description=notify the user %I if necessary
After=network-online.target

[Service]
User=%i
WorkingDirectory=~
ExecStart=/usr/bin/CTparentalnotify
Type=oneshot

[Install]
WantedBy=default.target

'
} > "/etc/systemd/system/CTparentalnotify@.service"

# on redémare le démon systemd pour prendre en compte ce nouveau service
systemctl daemon-reload
## on desactive les anciennes taches planifiés via systemd timer.
#for unite in $( systemctl list-unit-files | grep CTparentalskill | awk '{print $1}' )
systemctl list-unit-files | grep CTparentalskill | awk '{print $1}' | while read -r unite
do
systemctl stop $unite
systemctl disable $unite
done

#for unite in $( systemctl list-unit-files | grep CTparentalnotify | awk '{print $1}' )
systemctl list-unit-files | grep CTparentalnotify | awk '{print $1}' | while read -r unite
do
systemctl stop $unite
systemctl disable $unite
done

    #for PCUSER in $(listeusers)
    listeusers | while read -r PCUSER
    do
                {
    echo "[Unit]
Description=notify the user ${PCUSER} if necessary

[Timer]
OnBootSec=1min
OnUnitActiveSec=1min
Unit=CTparentalnotify@${PCUSER}.service

[Install]
WantedBy=timers.target
"
         } > /etc/systemd/system/CTparentalnotify${PCUSER}.timer
         systemctl enable CTparentalnotify${PCUSER}.timer
         systemctl start CTparentalnotify${PCUSER}.timer
    
    HOMEPCUSER=$(getent passwd "$PCUSER" | cut -d ':' -f6)
    HORAIRESPAM=""
      userisconfigured="0"

    while read line
    do

        if [ "$( echo "$line" | grep -E -c "^$PCUSER=[0-6]=" )" -eq 1 ] ; then
        echo "$line"
        NumDAY=$(echo "$line" | cut -d"=" -f2)
        h1=$(echo "$line" | cut -d"=" -f3 | cut -d":" -f1 | cut -d"h" -f1)
        m1=$(echo "$line" | cut -d"=" -f3 | cut -d":" -f1 | cut -d"h" -f2)
        h2=$(echo "$line" | cut -d"=" -f3 | cut -d":" -f2 | cut -d"h" -f1)
        m2=$(echo "$line" | cut -d"=" -f3 | cut -d":" -f2 | cut -d"h" -f2)
        h3=$(echo "$line" | cut -d"=" -f3 | cut -d":" -f3 | cut -d"h" -f1)
        m3=$(echo "$line" | cut -d"=" -f3 | cut -d":" -f3 | cut -d"h" -f2)
        h4=$(echo "$line" | cut -d"=" -f3 | cut -d":" -f4 | cut -d"h" -f1)
        m4=$(echo "$line" | cut -d"=" -f3 | cut -d":" -f4 | cut -d"h" -f2)
        if [ "$(echo -n "$h3""$m3" | wc -c)" -gt 2 ]; then
             if [ "$NumDAY" -eq 6 ] ; then
                HORAIRESPAM="$HORAIRESPAM${DAYSPAM[$NumDAY]}$h1$m1-$h2$m2|${DAYSPAM[$NumDAY]}$h3$m3-$h4$m4"

            else
                HORAIRESPAM="$HORAIRESPAM${DAYSPAM[$NumDAY]}$h1$m1-$h2$m2|${DAYSPAM[$NumDAY]}$h3$m3-$h4$m4|"
            fi
            
            {
            echo "[Unit]
Description=fermeture de la session de ${PCUSER} 1

[Timer]
# on attent 5 minute après le boot
OnCalendar=${DAYSSYSTEMD[$NumDAY]} *-*-* ${h2}:${m2}:00
Unit=CTparentalskill@${PCUSER}.service

[Install]
WantedBy=timers.target
"
            } > /etc/systemd/system/CTparentalskill${PCUSER}${DAYSSYSTEMD[$NumDAY]}1.timer
            
            {
            echo "[Unit]
Description=fermeture de la session de ${PCUSER} 2

[Timer]
# on attent 5 minute après le boot
OnCalendar=${DAYSSYSTEMD[$NumDAY]} *-*-* ${h4}:${m4}:00
Unit=CTparentalskill@${PCUSER}.service

[Install]
WantedBy=timers.target
"
            } > /etc/systemd/system/CTparentalskill${PCUSER}${DAYSSYSTEMD[$NumDAY]}2.timer
            systemctl enable CTparentalskill${PCUSER}${DAYSSYSTEMD[$NumDAY]}1.timer
            systemctl enable CTparentalskill${PCUSER}${DAYSSYSTEMD[$NumDAY]}2.timer
            systemctl start CTparentalskill${PCUSER}${DAYSSYSTEMD[$NumDAY]}1.timer
            systemctl start CTparentalskill${PCUSER}${DAYSSYSTEMD[$NumDAY]}2.timer
            
            userisconfigured="1"

        else
            if [ "$NumDAY" -eq 6 ] ; then
            HORAIRESPAM="$HORAIRESPAM${DAYSPAM[$NumDAY]}$h1$m1-$h2$m2"
            else
            HORAIRESPAM="$HORAIRESPAM${DAYSPAM[$NumDAY]}$h1$m1-$h2$m2|"
            fi
            {
            echo "[Unit]
Description=fermeture de la session de ${PCUSER} 1

[Timer]
# on attent 5 minute après le boot
OnCalendar=${DAYSSYSTEMD[$NumDAY]} *-*-* ${h2}:${m2}:00
Unit=CTparentalskill@${PCUSER}.service

[Install]
WantedBy=timers.target
"
            } > /etc/systemd/system/CTparentalskill${PCUSER}${DAYSSYSTEMD[$NumDAY]}1.timer
            systemctl enable CTparentalskill${PCUSER}${DAYSSYSTEMD[$NumDAY]}1.timer
            systemctl start CTparentalskill${PCUSER}${DAYSSYSTEMD[$NumDAY]}1.timer
            userisconfigured="1"
        fi
        fi
    done < $FILE_HCONF
    if [ $userisconfigured -eq 1 ] ; then
        echo "*;*;$PCUSER;$HORAIRESPAM" >> $FILEPAMTIMECONF
    else
        echo "*;*;$PCUSER;Al0000-2400" >> $FILEPAMTIMECONF
        $SED "/^$PCUSER=/d" $FILE_HCOMPT
        passwd -u "$PCUSER"
    fi
    done
    $SED "s?^HOURSCONNECT.*?HOURSCONNECT=ON?g" $FILE_CONF

}

function confgrub2() {
    PTNlogin='^[a-zA-Z]*$'
    ##Passage en keymap us pour le password comme ça quel que soit
    ##votre clavier le mot de passe correspond bien aux touches
    ##frappées. Ce qui évite de se prendre la tête pour le clavier
    ##avec le mot de passe grub.

    #apt-get install console-data
    layout1="$( grep "XKBLAYOUT" /etc/default/keyboard  | awk -F "\"" '{print $2}' | awk -F "," '{print $1}')"
    setxkbmap us
    loadkeys us
    clear
    gettext 'keymap is in qwerty us in grub menu.
    - Only letters or numbers.
    - 4 characters minimum.
Enter login to the superuser of grub2 :'
    while true; do
    read logingrub
    if [ "$(expr "$logingrub" : "$PTNlogin")" -gt 4  ];then
            break
    else
            clear
        gettext 'keymap is in qwerty us in grub menu.
    - Only letters or numbers.
    - 4 characters minimum.
Enter login to the superuser of grub2 :'
    fi
    done
    echo > /tmp/passgrub
    while [ "$(awk '{print $NF}' /tmp/passgrub | grep -c grub.)" -eq 0 ];do
    $NEWPASSGRUB2 | tee /tmp/passgrub
    done
    passwordgrub=$(awk '{print $NF}' /tmp/passgrub | grep grub.)
    ##on rebascule sur la keymap system
    setxkbmap "$layout1"
    loadkeys "$layout1"
    vide=""
    cat << EOF > /etc/grub.d/99_password
#!/bin/sh
## ce script doit être lancé en dernier !!!
## on restreint uniquement les menus de "setup uefi" , " recovery mode "
## ainsi que tous les submenu.
## seul les menuentry et submenu de premier niveau prennent en compte les paramètres d’accès utilisateurs.
## ce qui implique que l'ajout de --unrestricted a un submenu est récursif  !!
cat << ${vide}EOF
set superusers="$logingrub"
password_pbkdf2 $logingrub $passwordgrub
${vide}EOF
confunrestricted () {
        ## fonction lancée en tache de fond par la commande
        ## confunrestricted &
        ## elle attend la fin de l’exécution de tous les scripts  update grub
        ## puis modifie le fichier $BOOTREPGRUB2/grub.cfg pour y ajouter le droits a tout le monde
        cd /etc/grub.d/
        for file in *
        do
        if [ "\$(echo "\$file" | grep -E -c "[0-9][0-9]_")" -eq 1 ];then
            if [ -z "\$processupdategrub" ] ; then
                processupdategrub=\$file
            else
                processupdategrub=\$processupdategrub","\$file
            fi
        fi
        done
        while [ "\$(ps -C "\$processupdategrub" -o pid= | wc -l)" -gt 2 ]
        do
            sleep 0.2
        done
        sync
        cp $BOOTREPGRUB2/grub.cfg /tmp/grub.cfg.new
        while read -r linecfg
        do
            if [ "\$(echo "\$linecfg" | grep -E "menuentry " | grep -v "uefi-firmware" | grep -c -v "recovery mode" )" -eq 1 ];then
                line2=\$(echo "\$linecfg" | sed -e 's/ {/ --unrestricted { /g')
                sed -i "s|\$linecfg|\$line2|" $BOOTREPGRUB2/grub.cfg
            fi
        done < /tmp/grub.cfg.new
        rm /tmp/grub.cfg.new
    }
confunrestricted &
EOF
    chmod 755 /etc/grub.d/99_password
    update-grub2
}

function exportconf() {
    if [ ! -e "$FILEFIRWALLCONF" ] ;  then
    echo > "$FILEFIRWALLCONF"
    fi
    if [ ! -e "$FILEIPBLACKLIST" ] ;  then
    echo > "$FILEIPBLACKLIST"
    fi
    date="$( date +%y.%m.%d )"
    ## on ajoute un fichier indiquant la version majeur de ctparental ayant cree le fichier de conf
    VMAJEURACTUEL="$(cat $FILCHANGELOGGZ | gunzip | sed -n "1 p" | cut -d " " -f2 | sed "s/[().-]//g" | cut -c -3)"
    echo "VCONF=$VMAJEURACTUEL" > "$DIR_CONF"/VCONF
    FILEexpconf=${FILEexpconf:=$(echo "$DIRexpconf"/CTparental.conf."$date".tar.gz | sed -e "s|\/\{2,10\}|\/|g" )}
    tar -cvzf "$FILEexpconf" "$DIR_CONF"/wl-categories-available "$DIR_CONF"/categories-enabled.conf \
    "$DIR_CONF"/CThourscompteur "$DIR_CONF"/CTsafe.conf "$DIR_CONF"/bl-categories-available \
    "$DIR_CONF"/CThours.conf  "$DIR_CONF"/dnsfilter-available/ "$DIR_CONF"/ipv6filter-available/ "$DIR_CONF"/ipv4filter-available/ \
    "$DIR_CONF"/CTparental.conf "$DIR_CONF"/dip-rehabiliter.conf "$DIR_CONF"/dip-blackliste.conf \
    "$DIR_CONF"/GCToff.conf "$PRIVOXYCONF" "$PRIVOXYUSERA" "$PRIVOXYCTA" "$DIR_CONF"/VCONF \
    "$DIRE2G"lists/bannedmimetypelist "$DIRE2G"lists/bannedextensionlist "$DIRE2G"lists/bannedsitelist \
    "$FILEFIRWALLCONF" "$FILEIPBLACKLIST" /root/.ssh /home/ctsync/.ssh/ /etc/ssh/ "$DIR_CONF"/ctsync.conf 2>/dev/null
    rm -f "$DIR_CONF"/VCONF

    chmod 744 "$FILEexpconf"
    eval_gettext "Conf exported to \$FILEexpconf
"
}

function importconf() {
    # si l'archive contient bien la bonne liste de fichiers.
    dirtar=$(echo "$DIR_CONF" | sed -e "s/\///1")
    dir2gtar=$(echo "$DIRE2G" | sed -e "s/\///1")
    privoxyconftar=$(echo "$PRIVOXYCONF" | sed -e "s/\///1")
    privoxyuseratar=$(echo "$PRIVOXYUSERA" | sed -e "s/\///1")
    privoxyctatar=$(echo "$PRIVOXYCTA" | sed -e "s/\///1")
    filefirewallconftar=$(echo "$FILEFIRWALLCONF" | sed -e "s/\///1")
    fileipblacklisttar=$(echo "$FILEIPBLACKLIST" | sed -e "s/\///1")
    ## pour la compatibilitée client e2guardian <= serveur dansguardian
    if [ -d /etc/dansguardian ] ;then
        rm -rf /etc/dansguardian 
    fi
    ## si la version ctparental ayans genere le fichier de conf et trops differante on considaire le fichier non compatible.
    VMAJEURACTUEL="$(cat $FILCHANGELOGGZ | gunzip | sed -n "1 p" | cut -d " " -f2 | sed "s/[().-]//g" | cut -c -3)"
    tar -xvzf "$FILEimpconf" -C / "$dirtar"/VCONF 
    if [ $? -eq 0 ] ;then
        VCONF=$(grep "VCONF=" "$DIR_CONF"/VCONF | cut -d"=" -f2) 
        rm -f "$DIR_CONF"/VCONF
    else
        VCONF=0
    fi
    if [ $VMAJEURACTUEL -eq $VCONF ] ;then
        ## si on fait in import manuel
        if [ $clientsync -eq 0 ];then
            # si on a faire a une conf nftables
            if [ $(grep -i -c "nft" $FILEFIRWALLCONF) -ge 1 ] ; then 
               initfileiptables
            fi
            if [ -f "$DIR_CONF"/ctsync.conf ];then
                if [ "$( grep -c "SRVSYNC=ON" "$DIR_CONF"/ctsync.conf )" -eq 1 ];then
                    clientsyncoff
                    serversyncon
                    tar -xvzf "$FILEimpconf" -C / home/ctsync/.ssh/authorized_keys 
                    chown ctsync:ctsync /home/ctsync/.ssh/authorized_keys
                    chmod 644 /home/ctsync/.ssh/authorized_keys
                fi
                if [ "$( grep -c "CSYNC=ON" "$DIR_CONF"/ctsync.conf )" -eq 1 ];then
                    serversyncoff
                    useradd --shell /bin/bash --create-home --system ctsync
                    chmod 750 /home/ctsync
                    password=$(genpasswd)
                    echo "ctsync:$password" | chpasswd
                    tar -xvzf "$FILEimpconf" -C / home/ctsync/.ssh/
                    tar -xvzf "$FILEimpconf" -C / root/.ssh/
                    chown root:root /home/ctsync/.ssh/id_rsa
                    chmod 600 /home/ctsync/.ssh/id_rsa
                    ## on desactive les anciennes taches planifiés via systemd timer.
                    #for unite in $( systemctl list-unit-files | grep CTparentalcsync | awk '{print $1}' )
                    systemctl list-unit-files | grep CTparentalcsync | awk '{print $1}' | while read -r unite
                    do
                    systemctl stop $unite
                    systemctl disable $unite
                    done
                    {
                    echo '[Unit]
Description=sync on CTparental server
After=network-online.target

[Service]
User=root
WorkingDirectory=/root/
ExecStart=/usr/bin/CTparental -csync
Type=oneshot

[Install]
WantedBy=default.target

'
                    } > "/etc/systemd/system/CTparentalcsync.service"
                    # on redémare le démon systemd pour prendre en compte ce nouveau service
                    systemctl daemon-reload
                    {
                    echo "[Unit]
Description=sync on CTparental server

[Timer]
OnBootSec=10min
OnUnitActiveSec=10min
RandomizedDelaySec=5min
Unit=CTparentalcsync.service

[Install]
WantedBy=timers.target
"
                    } > /etc/systemd/system/CTparentalcsync.timer
                    systemctl enable CTparentalcsync.timer
                    systemctl start CTparentalcsync.timer
                fi
            fi
        else
            ## si l'import est éféctué par la syncro client serveur
            if [ ! "$(tar -tf "$FILEimpconf" | grep -c "$dir2gtar" )" -eq 1 ] ;then
                dir2gtar="etc/dansguardian/"
            fi
            tar -xvzf "$FILEimpconf" -C / "$dirtar"/wl-categories-available "$dirtar"/categories-enabled.conf \
            "$dirtar"/CThourscompteur "$dirtar"/CTsafe.conf "$dirtar"/dip-blackliste.conf "$dirtar"/bl-categories-available \
            "$dirtar"/CThours.conf  "$dirtar"/dnsfilter-available/ "$dirtar"/ipv4filter-available "$dirtar"/ipv6filter-available \
            "$dirtar"/CTparental.conf "$dirtar"/dip-rehabiliter.conf \
            "$dirtar"/GCToff.conf "$privoxyconftar" "$privoxyuseratar" "$privoxyctatar" \
            "$dir2gtar"lists/bannedmimetypelist "$dir2gtar"lists/bannedextensionlist "$dir2gtar"lists/bannedsitelist \
            "$filefirewallconftar" "$fileipblacklisttar"
            # si on a faire a une conf nftables
            if [ "$(grep -i -c "nft" $FILEFIRWALLCONF)" -ge 1 ] ; then 
                initfilenipables
            fi
            if [ -d /etc/dansguardian ] ;then
                cp -rf /etc/dansguardian/*  "$DIRE2G"
                rm -rf /etc/dansguardian
            fi
        fi
        $SED "s?^MD5DREAB.*?MD5DREAB=old?g" $FILE_CONF
        $SED "s?^MD5IPT.*?MD5IPT=old?g" $FILE_CONF
        FILTRAGEISOFF="$( grep -c "DNSMASQ=OFF" $FILE_CONF )"
        ## on patch si besoins les fichiers de categories imprter d'un server sous nftable.
        if [ $(grep "add ipv4filter" $DIR_IPV4_FILTER_AVAILABLE/* | wc -l) -eq 0 ] ; then
            for category in $(ls -1 $DIR_IPV4_FILTER_AVAILABLE | cut -d '@' -f1)
            do
                $SED "s/^/add ipv4filter /" $DIR_IPV4_FILTER_AVAILABLE/$category
                $SED "s/^/add ipv6filter /" $DIR_IPV6_FILTER_AVAILABLE/$category
            done
        fi
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            adapt
            catChoice
            dnsmasqon
        else
            desactivegourpectoff
            autoupdateoff
            dnsmasqoff
            FILTRAGEISOFF=1
            iptablesreload
        fi
        if [ "$( grep -c GCTOFF=ON $FILE_CONF )" -eq 1 ];then
            activegourpectoff
        else
            desactivegourpectoff
        fi
        if [ "$( grep -c HOURSCONNECT=ON $FILE_CONF )" -eq 1 ];then
            readTimeFILECONF
        else
            desactivetimelogin
        fi
        if [ "$( grep -c "REDIRECT=ON" $FILE_CONF )" -eq 1 ];then
            redirecton
        else
            redirectoff
        fi
    else
        VCOMPATIBLE=$(echo "$(cat $FILCHANGELOGGZ | gunzip | sed -n "1 p" | cut -d " " -f2 | cut -c -5).xx-x.x)" )
        if [ $clientsync -eq 0 ];then
            eval_gettext "\$FILEimpconf is not a compatible configuration file"
            echo ""
        else
            eval_gettext "the CTparental server version is not \$VCOMPATIBLE"
            echo ""
        fi
    fi
}

function genpasswd() {
  local length=${1:-8}
  tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${length} | xargs
}
function expsync () {
    if [ "$(grep -c "SRVSYNC=ON" "$DIR_CONF"/ctsync.conf )" -eq 1 ];then
    if [ ! -e "/home/ctsync/MD5EXPSYNC.txt" ] ;  then
        touch "/home/ctsync/MD5EXPSYNC.txt"
    fi
     md5old=$(cat "/home/ctsync/MD5EXPSYNC.txt" | cut -d" " -f1)
     md5new="$({ cat "$DIR_CONF"/wl-categories-available "$DIR_CONF"/categories-enabled.conf \
 "$DIR_CONF"/CThourscompteur "$DIR_CONF"/CTsafe.conf "$DIR_CONF"/dip-blackliste.conf "$DIR_CONF"/bl-categories-available \
 "$DIR_CONF"/CThours.conf  "$DIR_CONF"/dnsfilter-available/* "$DIR_CONF"/ipv6filter-available/* "$DIR_CONF"/ipv4filter-available/* \
 "$DIR_CONF"/CTparental.conf "$DIR_CONF"/dip-rehabiliter.conf \
 "$DIR_CONF"/GCToff.conf "$PRIVOXYCONF" "$PRIVOXYUSERA" "$PRIVOXYCTA" \
 "$DIRE2G"lists/bannedmimetypelist "$DIRE2G"lists/bannedextensionlist "$DIRE2G"lists/bannedsitelist \
 "$FILEFIRWALLCONF" "$FILEIPBLACKLIST" /home/ctsync/.ssh/authorized_keys | md5sum | cut -d" " -f1 
 })"
        if [ ! "$md5old" = "$md5new" ]; then
        FILEexpconf="/home/ctsync/confCTparental.tar.gz"
        exportconf
        echo $md5new > /home/ctsync/MD5EXPSYNC.txt
        md5sum /home/ctsync/confCTparental.tar.gz > /home/ctsync/confCTparental.tar.gz.md5
        fi
    fi
}
function serversyncon () {
    echo "<serversyncon>"
    $ENABLESSH
    if [ "$(grep -c "CSYNC=ON" "$DIR_CONF"/ctsync.conf)" -eq 1 ] ;then
        echo "$(gettext "You must first disable client mode")"
    else
            if [ "$i_WAN_ipv6" =  "" ];then
            i_WAN=$i_WAN_ipv4
            SRVipv6linklocal=$(ip addr show $i_WAN_ipv4  | grep inet6 | awk '{print $2}' | grep "fe80" | cut -d"/" -f1)
            else
            i_WAN=$i_WAN_ipv6
            SRVipv6linklocal=$(ip addr show $i_WAN_ipv6  | grep inet6 | awk '{print $2}' | grep "fe80" | cut -d"/" -f1)
            fi
            useradd --shell /bin/bash --create-home --system ctsync 2>/dev/null
            chown root:ctsync /home/ctsync
            chmod 770 /home/ctsync
            passwordsrv=$(genpasswd)
            echo "ctsync:$passwordsrv" | chpasswd
            rm -rf /home/ctsync/.ssh
            mkdir -p /home/ctsync/.ssh
            touch /home/ctsync/.ssh/authorized_keys
            chown ctsync:ctsync /home/ctsync/.ssh/authorized_keys
            chmod 644 /home/ctsync/.ssh/authorized_keys
            SFTPPATH=$(find / -type f -name sftp-server -executable 2>/dev/null)
            { echo "
Port $PORTSSH
AddressFamily inet6
ListenAddress ${SRVipv6linklocal}%${i_WAN}
#ListenAddress ::
#SyslogFacility AUTH
#LogLevel INFO
StrictModes yes
PubkeyAuthentication yes
AuthorizedKeysFile    .ssh/authorized_keys
PasswordAuthentication no
PermitEmptyPasswords no
UsePAM no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
PrintMotd no
Banner none
AcceptEnv LANG LC_*
# override default of no subsystems
Subsystem    sftp    $SFTPPATH
Match User ctsync
        PasswordAuthentication yes
        ForceCommand /usr/bin/CTctsync_ssh
        AllowTcpForwarding no"
        
} > /etc/ssh/sshd_config
        $SSHrestart

        {
        echo "# $(gettext "to enable sync with this server, run the following commands on the client on your local network that you want to synchronize")
CTparental -syncon \"$SRVipv6linklocal\" \"$passwordsrv\" \"$PORTSSH\"

SRVipv6linklocal=$SRVipv6linklocal
SRVSYNC=ON
CSYNC=OFF
PORTSSH=$PORTSSH
"
        } > "$DIR_CONF"/ctsync.conf
        cat "$DIR_CONF"/ctsync.conf
        chown root:"$GROUPHTTPD" "$DIR_CONF"/ctsync.conf
        chmod 640 "$DIR_CONF"/ctsync.conf
        expsync > /dev/null
        {
     echo '[Unit]
Description=expsync off CTparental server
After=network-online.target

[Service]
User=root
WorkingDirectory=/root/
ExecStart=/usr/bin/CTparental -expsync
Type=oneshot

[Install]
WantedBy=default.target

'
        } > "/etc/systemd/system/CTparentalexpsync.service"
        # on redémare le démon systemd pour prendre en compte ce nouveau service
        systemctl daemon-reload

        {
        echo "[Unit]
Description=expsync off CTparental server

[Timer]
OnBootSec=10min
OnUnitActiveSec=15min
Unit=CTparentalexpsync.service

[Install]
WantedBy=timers.target
"
        } > /etc/systemd/system/CTparentalexpsync.timer
         systemctl enable CTparentalexpsync.timer
         systemctl start CTparentalexpsync.timer

    fi
echo "</serversyncon>"
}

function serversyncoff () {
    $SSHstop
    pkill -u ctsync
    deluser --quiet --system --remove-home ctsync 
    ## on desactive les anciennes taches planifiés via systemd timer.
    #for unite in $( systemctl list-unit-files | grep CTparentalcsync | awk '{print $1}' )
    systemctl list-unit-files | grep CTparentalcsync | awk '{print $1}' | while read -r unite
    do
        systemctl stop $unite
        systemctl disable $unite
    done
    rm -f /etc/systemd/system/CTparentalexpsync*
    systemctl daemon-reload
    $SED "s?^SRVSYNC=.*?SRVSYNC=OFF?g" "$DIR_CONF"/ctsync.conf
    $DISABLESSH
}

function clientsyncon () {
    echo "<clientsyncon>"
    if [ "$i_WAN_ipv6" =  "" ];then
            i_WAN=$i_WAN_ipv4
    else
            i_WAN=$i_WAN_ipv6
    fi
    SRVipv6linklocal=$1
    passwordsrv=$2
    PORTSSH=$3
    if [ "$( grep -c "SRVSYNC=ON" "$DIR_CONF"/ctsync.conf )" -eq 1 ];then
        echo "$(gettext "You must first disable server mode")"
    else
        useradd --shell /bin/bash --create-home --system ctsync
        chown root:ctsync /home/ctsync
        chmod 770 /home/ctsync
        password=$(genpasswd)
        echo "ctsync:$password" | chpasswd
        rm -rf /home/ctsync/.ssh
        mkdir -p /home/ctsync/.ssh
        ## pour les distributions basée sur ubuntu évite des erreurs ssh-copy-id
        export HOME=/root
        mkdir -p /root/.ssh
        echo "$(gettext "The requested password is:")
    $passwordsrv
    "
        ssh-keygen -t rsa -b 2048 -P "" -f /home/ctsync/.ssh/id_rsa -q
        chown root:root /home/ctsync/.ssh/id_rsa
        chmod 600 /home/ctsync/.ssh/id_rsa
        ssh-copy-id -i /home/ctsync/.ssh/id_rsa.pub -p $PORTSSH ctsync@${SRVipv6linklocal}%${i_WAN}
        
        ## on desactive les anciennes taches planifiés via systemd timer.
        #for unite in $( systemctl list-unit-files | grep CTparentalcsync | awk '{print $1}' )
        systemctl list-unit-files | grep CTparentalcsync | awk '{print $1}' | while read -r unite
        do
        systemctl stop $unite
        systemctl disable $unite
        done
        
         {
     echo '[Unit]
Description=sync on CTparental server
After=network-online.target

[Service]
User=root
WorkingDirectory=/root/
ExecStart=/usr/bin/CTparental -csync
Type=oneshot

[Install]
WantedBy=default.target

'
        } > "/etc/systemd/system/CTparentalcsync.service"
        # on redémare le démon systemd pour prendre en compte ce nouveau service
        systemctl daemon-reload

        {
        echo "[Unit]
Description=sync on CTparental server

[Timer]
OnBootSec=10min
OnUnitActiveSec=10min
RandomizedDelaySec=5min
Unit=CTparentalcsync.service

[Install]
WantedBy=timers.target
"
        } > /etc/systemd/system/CTparentalcsync.timer
         systemctl enable CTparentalcsync.timer
         systemctl start CTparentalcsync.timer
        {
        echo "
SRVipv6linklocal=$SRVipv6linklocal
PORTSSH=$PORTSSH
CSYNC=ON
SRVSYNC=OFF
"
        } > "$DIR_CONF"/ctsync.conf
        chown root:"$GROUPHTTPD" "$DIR_CONF"/ctsync.conf
        chmod 640 "$DIR_CONF"/ctsync.conf
        clientsync
    fi
    echo "</clientsyncon>"
}

function clientsyncoff () {
    pkill -u ctsync
    deluser --quiet --system --remove-home ctsync
    ## on desactive les anciennes taches planifiés via systemd timer.
    #for unite in $( systemctl list-unit-files | grep CTparentalcsync | awk '{print $1}' )
    systemctl list-unit-files | grep CTparentalcsync | awk '{print $1}' | while read -r unite
    do
        systemctl stop $unite
        systemctl disable $unite
    done
    rm -f /etc/systemd/system/CTparentalcsync*
    systemctl daemon-reload
    $SED "s?^CSYNC=.*?CSYNC=OFF?" "$DIR_CONF"/ctsync.conf

}

function clientsync () {
    if [ "$i_WAN_ipv6" =  "" ];then
            i_WAN=$i_WAN_ipv4
    else
            i_WAN=$i_WAN_ipv6
    fi
    export HOME=/root
    SRVipv6linklocal=$(grep "SRVipv6linklocal=" "$DIR_CONF"/ctsync.conf | cut -d"=" -f2)
    echo $SRVipv6linklocal
    PORTSSH=$(grep "PORTSSH=" "$DIR_CONF"/ctsync.conf | cut -d"=" -f2)
    rsync --chmod 755 -av -e "ssh -i /home/ctsync/.ssh/id_rsa -p $PORTSSH" ctsync@[${SRVipv6linklocal}%${i_WAN}]:/home/ctsync/confCTparental.tar.gz.md5 /home/ctsync/confCTparental.tar.gz.md5
    error1=$?
    rsync --chmod 755 -av -e "ssh -i /home/ctsync/.ssh/id_rsa -p $PORTSSH" ctsync@[${SRVipv6linklocal}%${i_WAN}]:/home/ctsync/confCTparental.tar.gz /home/ctsync/confCTparental.tar.gz
    error2=$?
    if [ $(( $error1 + $error2 )) -ge 1 ] ;then
    exit 1
    fi
    md5fileorig=$(grep " " "/home/ctsync/confCTparental.tar.gz.md5" | cut -d" " -f1)
    md5filenew=$( md5sum /home/ctsync/confCTparental.tar.gz | cut -d" " -f1 )
    ## on sassure que les fichiers sont pas corrompus.
    if [ "$md5fileorig" = "$md5filenew" ]; then
        if [ -f /home/ctsync/confCTparental.tar.gz.md5.old ];then
            echo "$md5fileorig  = $md5filenew"
            md5fileorig=$(grep " " "/home/ctsync/confCTparental.tar.gz.md5.old" | cut -d" " -f1)
            ## on verifie si il y a un changement dans la conf
            if [ ! "$md5fileorig" = "$md5filenew" ]; then
                FILEimpconf=/home/ctsync/confCTparental.tar.gz
                clientsync=1
                importconf
                md5sum /home/ctsync/confCTparental.tar.gz > /home/ctsync/confCTparental.tar.gz.md5.old
            fi
        else
            FILEimpconf=/home/ctsync/confCTparental.tar.gz
            clientsync=1
            importconf
            md5sum /home/ctsync/confCTparental.tar.gz > /home/ctsync/confCTparental.tar.gz.md5.old
        fi
    fi
}
function redirecton () {
    cp -f "$DIR_SHARE"/www/CTparental/index.php "$DIRHTML"/index.php
    cp -f "$NEWTEMPLETE2G"/template.html "$DIRE2GLANG"/ukenglish/template.html
    cp -f "$NEWTEMPLETE2G"/template-fr.html "$DIRE2GLANG"/french/template.html
    chown -R root:"$GROUPHTTPD" "$DIRHTML"
    echo $E2GUARDIANrestart
    $E2GUARDIANrestart
    iptablesreload
    $SED "s?^REDIRECT=.*?REDIRECT=ON?"  "$FILE_CONF"
}
function redirectoff () {
    cp -f "$DIR_SHARE"/www/CTparental/index2.php "$DIRHTML"/index.php
    cp -f "$DIR_SHARE"/www/CTparental/index2.php "$DIRE2GLANG"/ukenglish/template.html
    cp -f "$DIR_SHARE"/www/CTparental/index2.php "$DIRE2GLANG"/french/template.html
    chown -R root:"$GROUPHTTPD" "$DIRHTML"
    $E2GUARDIANrestart
    iptablesreload
    $SED "s?^REDIRECT=.*?REDIRECT=OFF?"  "$FILE_CONF"
}
# and func # ne pas effacer cette ligne !!

usage="$(gettext "Use"): CTparental    {-i }|{ -u }|{ -dl }|{ -ubl }|{ -rl }|{ -on }|{ -off }|{ -cble }|{ -dble }
             |{ -tlo }|{ -tlu }|{ -uhtml }|{ -aupon }|{ -aupoff }|{ -aup }
-i$(gettext "        => Install parental control on the computer (desktop PC). Can be used with
          an additional parameter to specify a source path for the redirection page.
          example: CTparental -i -dirhtml /home/toto/html/
          if no option a default page is used.")
-u$(gettext "        => uninstall the Parental Control Computer (desktop PC)")
-dl$(gettext "        => updates parental control from the blacklist of the University of Toulouse")
-ubl$(eval_gettext "        => To be done after each change of the file \$BL_DIPOSSI")
-rl$(eval_gettext "        => To be done after each change of the file \$REABDIP")
-on$(gettext "        => Enable parental control")
-off$(gettext "        => Disable parental control")
-cble$(gettext "        => Set the filter mode by whitelist or blacklist (default)
          and the categories that you want to activate.")
-dble$(gettext "        => Reset the default active categories and blacklist filtering.")
-tlo$(gettext "        => Enable and configure the login time restrictions for users.")
-tlu$(gettext "        => Disable the login time restrictions for users.")
-uhtml$(gettext "        => updates the redirect page from a source directory or default.
          examples:
                  - With a source directory: CTparental -uhtml -dirhtml /home/toto/html/
                  - Default: CTparental -uhtml
          also lets you change the login couple password of the web interface.")
-aupon$(gettext "        => Enable the automatic update of the Toulouse blacklist (every 7 days).")
-aupoff$(gettext "        => Disable the automatic update of the Toulouse blacklist.")
-aup$(gettext "        => as -dl but only if there is no update for more than 7 days.")
-nodep$(gettext "        => if placed after -i or -u allows not install / uninstall the dependencies, useful if
          we prefer to install them by hand, or for the postinst and prerm script of deb.
          examples:
                  CTparental -i -nodep
                  CTparental -i -dirhtml /home/toto/html/ -nodep
                  CTparental -u -nodep")
-nomanuel$(gettext "   => used only for the postinst and prerm script.")
-gcton$(eval_gettext "        => Enable a group of privileged users that will not undergo filtering.
          exemples:
                  CTparental -gctulist
                  Comment all users that you want to filter in \$FILE_GCTOFFCONF
                  CTparental -gctalist")
-gctoff$(gettext "        => Disable privileged group.")
          $(gettext "all users of the system undergo the filtering!")
-gctalist$(eval_gettext "   => Add / Delete users in the ctoff group based on the config file, \$FILE_GCTOFFCONF")
-ipton$(gettext "        => Enable rules of custom firewall.")
-iptoff$(gettext "        => Disable rules of custom firewall.")
-grubPon$(gettext "    => Enable the superuser of grub2.")
-grubPoff$(gettext "   => Disable the superuser of grub2.")
-pfoff$(gettext "        => Disable default rules privoxy.")
-pfon$(gettext "        => Enable default rules privoxy. (default is Enable)")
-ron$(gettext "        => Enable redirect page.")
-roff$(gettext "        => Disabled redirect page.")
-exp$(gettext "        => Export configuration.
          exemple:
                  CTparental -exp /home/myhomedir/")
-imp$(gettext "        => Import a configuration.
          exemple:
                  CTparental -imp /home/myhomedir/CTparental.conf.yy.mm.dd.tar.gz")
-logdnson$(gettext "   => For debugging only.
          Enabling dnsmasq query log in the /var/log/dnsmasq.query.log file.")
-logdnsoff$(gettext "  => To disable dnsmasq query log in /var/log/dnsmasq.query.log .")
-setadmin$(gettext "    => To change the login couple password.")
-expsync$(gettext "    => To update the conf distribute by the server.")
-srvon$(gettext "    => To activate the server role.")
-srvoff$(gettext "    => to disable the server role.")
-syncon$(gettext "    => To activate the client role.")
-syncoff$(gettext "    => to disable the client role.")
-csync$(gettext "    => To synchronize the client with the server.")
"
arg1=${1}
case $arg1 in
    -\? | -h* | --h*)
        echo "$usage"
    ;;
    -i )
        if [ $# -ge 2 ]; then
            if [ $2 = "-dirhtml" ]; then
                if [ $# -ge 3 ]; then
                    DIRhtmlPersonaliser=$3
                    if [ ! -d "$DIRhtmlPersonaliser" ];then
                        gettext 'Invalid directory path!'
                        exit 0
                    fi
                    if [ $# == 4 ]; then
                        if [ $4 = "-nodep" ]; then
                            noinstalldep=1
                        fi
                    fi
                else
                    echo "$(gettext "Missing argument, wwwCTadminPath")";
                    echo "CTparental -uhtml -dirhtml \"/dir/wwwCTadminPath\" ";
                fi
            fi
            
            if [ $2 = "-nodep" ]; then
                noinstalldep=1
            fi
            if [ $# == 3 ]; then
                if [ $3 = "-nomanuel" ]; then
                    nomanuel=1
                fi
            fi
        fi
        networkisoknext
        install
    ;;
    -u )
        if [ $# -ge 2 ]; then
            if [ $2 = "-nodep" ]; then
                noinstalldep=1
            fi
        fi
        if [ $# -ge 3 ]; then
            if [ $3 = "-nomanuel" ]; then
                nomanuel=1
            fi
        fi
        uninstall
    ;;
    -dl )
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            networkisoknext
            download
            adapt
            catChoice
            dnsmasqon
            $SED "s?^LASTUPDATE.*?LASTUPDATE=$THISDAYS=$(date +%d-%m-%Y\ %T)?" $FILE_CONF
        fi
    ;;
    -ubl )
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            networkisoknext
            adapt
            catChoice
            dnsmasqon
        fi
    ;;
    -uhtml )
        if [ ! -z $2 ];then
            if [ $2 = "-dirhtml" ]; then
                if [ $# == 3 ]; then
                    DIRhtmlPersonaliser=$3
                    if [ ! -d "$DIRhtmlPersonaliser" ];then
                        gettext 'Invalid directory path!'
                        exit 0
                    else
                        networkisoknext
                        FoncHTTPDCONF
                    fi
                else
                    echo "$(gettext "Missing argument, wwwCTadminPath")";
                    echo "CTparental -uhtml -dirhtml \"/dir/wwwCTadminPath\" ";
                    exit 0
                fi
            fi
        else
            networkisoknext
            FoncHTTPDCONF
        fi
    ;;
    -rl )
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            networkisoknext
            catChoice
            dnsmasqon
        fi
    ;;
    -on )
        networkisoknext
        FILTRAGEISOFF=0
        dnsmasqon
        iptablesreload
        activegourpectoff
    ;;
    -off )
        desactivegourpectoff
        autoupdateoff
        dnsmasqoff
        FILTRAGEISOFF=1
        iptablesreload
    ;;
    -wlo )
    if [ ! "$FILTRAGEISOFF" -eq 1 ];then
        networkisoknext
        dnsmasqwhitelistonly
    fi
    ;;
    -cble )
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            networkisoknext
            choiblenabled
            catChoice
            dnsmasqon
        fi
    ;;
    -dble )
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            networkisoknext
            initblenabled
            catChoice
            dnsmasqon
        fi
    ;;
    -tlo )
        activetimelogin
    ;;
    -tlu )
        desactivetimelogin
    ;;
    -trf )
        readTimeFILECONF
    ;;
    -aupon )
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            autoupdateon
        fi
    ;;
    -aupoff )
        autoupdateoff
    ;;
    -gcton )
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            networkisoknext
            activegourpectoff
            iptablesreload
        fi
    ;;
    -gctoff )
        desactivegourpectoff
        iptablesreload
    ;;
    -gctulist )
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            updatelistgctoff
        fi
    ;;
    -gctalist )
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            networkisoknext
            if [ "$(updatelistgctoff)" -eq 1 ];then
                updatecauser
            fi
            unset test
            applistegctoff
            iptablesreload
        fi
    ;;
    -ipton )
        networkisoknext
        $SED "s?.*IPRULES.*?IPRULES=ON?" $FILE_CONF
        iptdisableconflict
        iptablesreload
        echo -e "$RougeD $(eval_gettext 'to add custom rules edit the file 
$FILEFIRWALLCONF 
then run the command CTparental -ipton') 

$(eval_gettext 'to add ipv4/ipv6 blacklist edit the file 
$FILEIPBLACKLIST 
then run the command CTparental -ipton') 
 $Fcolor"
    ;;
    -iptoff )
        $SED "s?.*IPRULES=.*?IPRULES=OFF?" $FILE_CONF
        iptdisableconflict
        iptablesreload
        rm -f $RSYSLOGCTPARENTAL
        $RSYSLOGRESTART
    ;;
    -cron )
        # appelé toutes les minutes par cron pour activer/désactiver
        # les usagers ayant des restrictions de temps journalier de
        # connexion.
        if [ "$( grep -c "HOURSCONNECT=ON" $FILE_CONF )" -eq 1 ];then
            updatetimelogin
        fi
        if [ ! "$FILTRAGEISOFF" -eq 1 ];then
            # appelé toutes les minutes par cron pour modifier la
            # configuration en cas de changement de réseau.
            nomade
            # appelé toutes les minutes par cron pour activer le
            # filtrage sur les usagers nouvellement créés.
            if [ $(updatelistgctoff) -eq 1 ];then
            applistegctoff
            iptablesreload
            fi
            updatecauser
        fi
    ;;
    -dgreload )
        $E2GUARDIANrestart
    ;;
    -grubPon )
        confgrub2
    ;;
    -grubPoff )
        rm -rf /etc/grub.d/99_password
        update-grub2
    ;;
    -pfoff )
        privoxydefaultfilteroff
    ;;
    -pfon )
        privoxydefaultfilteron
    ;;
    -ron )
        redirecton
    ;;
    -roff )
        redirectoff
    ;;
    -logdnson )
        {
            echo "log-queries"
            echo "log-facility=/var/log/dnsmasq.query.log"
        } > "$DIR_DNS_BLACKLIST_ENABLED"/dnsmasq.query.log.conf
        resolvconffixon
    ;;
    -logdnsoff )
        rm -f "$DIR_DNS_BLACKLIST_ENABLED"/dnsmasq.query.log.conf
        resolvconffixon
        rm -f /var/log/dnsmasq.query.log
    ;;
    -exp )
        if [ $# == 2 ]; then
            DIRexpconf=$2
            if [ ! -d "$DIRexpconf" ];then
                gettext 'Invalid directory path!'
                exit 0
            fi
        else
            echo "$(gettext "Missing argument, directory path")";
            echo "CTparental -exp \"/directory/path\"";
            exit 0
        fi
        exportconf
    ;;
    -imp )
        if [ $# == 2 ]; then
            FILEimpconf=$2
            if [ ! -e "$FILEimpconf" ];then
                gettext 'Error opening the file'
                exit 0
            fi
        else
            echo "$(gettext "Missing argument, fileconf path")";
            echo "CTparental -imp \"/directory/fileconf\"";
            exit 0
        fi
        importconf
    ;;
    -cainstall )
        updatecauser
    ;;
    -setadmin )
        if [ $# == 3 ]; then
            addadminhttpdapr1md5php $2 $3
        else
            echo "$(gettext "Missing argument, login or password")";
            echo "CTparental -setadmin \"login\" \"password\" ";
        fi
    ;;
    -srvon )
        serversyncon
    ;;
    -srvoff )
        serversyncoff
    ;;
    -expsync )
        expsync
    ;;
    -syncon )
        if [ $# == 4 ]; then
            clientsyncon $2 $3 $4
        else
        echo "$(gettext "Missing argument, Ipv6 server or password or port")"
        echo "CTparental -syncon \"fe80::ffff:eeee:dddd:aaaa\" \"srvpassword\" \"22\" ";
        fi
    ;;
    -syncoff )
        clientsyncoff
    ;;
    -csync )
        clientsync
    ;;
    -v )
    if [ "$(grep -c 'SRVHTTP="nginx"' $DIR_CONF/dist.conf)" -eq 1 ];then
    NUMVER="nginx_"$NUMVER
    else
    NUMVER="lighttpd_"$NUMVER
    fi
    if [ "$(grep -c 'confe2guardian' /usr/bin/CTparental)" -ge 2 ];then
    NUMVER="full_"$NUMVER
    else
    NUMVER="min_"$NUMVER
    fi
    if [ "$(grep -c 'nftablesreload' /usr/bin/CTparental)" -ge 2 ];then
    NUMVER="nftables_"$NUMVER
    else
    NUMVER="iptables_"$NUMVER
    fi
    echo "$NUMVER"
    ;;
    *)
    echo "$(gettext "Unknown argument"):$1";
    echo "$usage";
    exit 1
    ;;
esac

rm -rf $PIDFILE

exit 0
