Subversion Repositories ALCASAR

Rev

Rev 3020 | Rev 3035 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log

#!/bin/bash
#  $Id: alcasar.sh 3021 2022-06-06 21:24:25Z rexy $

# ALCASAR is a Free and open source NAC (Network Access Controler) created by Franck BOUIJOUX (3abtux), Pascal LEVANT and Richard REY (Rexy)
# ALCASAR is based on a stripped Mageia (LSB) with the following open source softwares Coovachilli, freeradius, mariaDB, lighttpd, php, netfilter, e2guardian, ntpd, openssl, dnsmasq, unbound, gammu, clamav, Ulog, fail2ban, vnstat, wkhtml2pdf, ipt_NETFLOW, NFsen and NFdump
# contact : info@alcasar.net

# Install script for ALCASAR (a secured and authenticated Internet access control captive portal)
# This script is distributed under the Gnu General Public License (GPLV3)

# Options :
#       -i or --install
#       -u or --uninstall
# Functions :
#       system_testing  : Free space test and mageia version test
#       network_testing : Internet connectivity tests
#       init                    : Installation of RPM and scripts
#       network                 : Network parameters
#       ACC                             : ALCASAR Control Center installation
#       CA                              : Certification Authority initialization
#       time_server             : NTPd configuration
#       init_db                 : Initilization of radius database managed with MariaDB
#       freeradius              : FreeRadius initialisation
#       chilli                  : Coovachilli initialisation (+authentication page)
#       e2guardian              : E2Guardian filtering HTTP proxy configuration
#       antivirus               : Clamav & freshclam configuration
#       ulogd                   : Log system in userland (match NFLOG target of iptables)
#       nfsen                   : Configuration of Netflow grapher (nfsen) & netflow collector (nfcapd)
#       unbound                 : Name server configuration
#       dnsmasq                 : Name server configuration (for whitelist ipset support)
#       vnstat                  : Little network stat daemon
#       BL                              : Adaptation of Toulouse University BlackList : split into 3 BL (for unbound, for e2guardian and for Netfilter)
#       cron                    : Logs export + watchdog + connexion statistics
#       fail2ban                : Fail2ban IDS installation and configuration
#       gammu_smsd              : Autoregister addon via SMS (gammu-smsd)
#       msec                    : Mageia security package configuration
#       letsencrypt             : Let's Encrypt client
#       mail_service    : Mail service for email authentification method
#       post_install    : Security, log rotation, etc.

DEBUG_ALCASAR='off'; export DEBUG_ALCASAR       # Debug mode = wait (hit key) after each function
DATE=`date '+%d %B %Y - %Hh%M'`
DATE_SHORT=`date '+%d/%m/%Y'`
Lang=`echo $LANG|cut -c 1-2`
mode="install"
# ******* Files parameters - paramètres fichiers *********
DIR_INSTALL=`pwd`                                               # current directory
DIR_CONF="$DIR_INSTALL/conf"                    # install directory (with conf files)
DIR_SCRIPTS="$DIR_INSTALL/scripts"              # install directory (with script files)
DIR_BLACKLIST="$DIR_INSTALL/blacklist"  # install directory (with blacklist files)
DIR_SAVE="/var/Save"                                    # backup directory (traceability_log, user_db, security_log)
DIR_WEB="/var/www/html"                                 # directory of Lighttpd
DIR_DG="/etc/e2guardian"                                # directory of E2Guardian
DIR_ACC="$DIR_WEB/acc"                                  # directory of the 'ALCASAR Control Center'
DIR_DEST_BIN="/usr/local/bin"                   # directory of ALCASAR scripts
DIR_DEST_ETC="/usr/local/etc"                   # directory of ALCASAR conf files
DIR_DEST_SHARE="/usr/local/share"               # directory of share files used by ALCASAR (unbound for instance)
CONF_FILE="$DIR_DEST_ETC/alcasar.conf"  # central ALCASAR conf file
PASSWD_FILE="/root/ALCASAR-passwords.txt"       # text file with the passwords and shared secrets
# ******* DBMS parameters - paramètres SGBD ********
DB_RADIUS="radius"                                              # database name used by FreeRadius server
DB_USER="radius"                                                # user name allows to request the users database
DB_GAMMU="gammu"                                                # database name used by Gammu-smsd
# ******* Network parameters - paramètres réseau *******
HOSTNAME="alcasar"                                              # default hostname
DOMAIN="localdomain"                                    # default local domain
EXTIF=''                                                                # EXTIF is connected to the ISP broadband modem/router (In France : Box-FAI)
INTIF=''                                                                # INTIF is connected to the consultation network
MTU="1500"
DEFAULT_PRIVATE_IP_MASK="192.168.182.1/24"      # Default ALCASAR IP address
# ****** Paths - chemin des commandes *******
SED="/bin/sed -i"
# ****************** End of global parameters *********************

license()
{
        if [ $Lang == "fr" ]
        then
                cat $DIR_INSTALL/gpl-warning.fr.txt | more
        else
                cat $DIR_INSTALL/gpl-warning.txt | more
        fi
        response=0
        PTN='^[oOyYnN]?$'
        until [[ "$response" =~ $PTN ]]
        do
                if [ $Lang == "fr" ]
                        then echo -n "Acceptez-vous les termes de cette licence (O/n)? : "
                        else echo -n "Do you accept the terms of this license (Y/n)? : "
                fi
                read response
        done
        if [ "$response" = "n" ] || [ "$response" = "N" ]
        then
                exit 1
        fi
} # End of license()

header_install()
{
        clear
        echo "-----------------------------------------------------------------------------"
        echo "                     ALCASAR V$VERSION Installation"
        echo "Application Libre pour le Contrôle d'Accès Sécurisé et Authentifié au Réseau"
        echo "-----------------------------------------------------------------------------"
} # End of header_install()

########################################################
##                  "system_testing"                  ##
## - Test Mageia version                              ##
## - Test ALCASAR version (if already installed)      ##
## - Test free space on /var  (>10G)                  ##
## - Test Internet access                             ##
########################################################
system_testing()
{
# Test of Mageia version
# extract the current Mageia version and hardware architecture (i586 ou X64)
        fic=`cat /etc/product.id`
        unknown_os=0
        old="$IFS"
        IFS=","
        set $fic
        for i in "$@"
        do
                if [ "`echo $i|grep distribution|cut -d'=' -f1`" == "distribution" ]
                        then
                        DISTRIBUTION=`echo $i|cut -d"=" -f2`
                        unknown_os=`expr $unknown_os + 1`
                fi
                if [ "`echo $i|grep version|cut -d'=' -f1`" == "version" ]
                        then
                        CURRENT_VERSION=`echo $i|cut -d"=" -f2`
                        unknown_os=`expr $unknown_os + 1`
                fi
                if [ "`echo $i|grep arch|cut -d'=' -f1`" == "arch" ]
                        then
                        ARCH=`echo $i|cut -d"=" -f2`
                        unknown_os=`expr $unknown_os + 1`
                fi
        done
        if [ "$ARCH" != "x86_64" ]
                then
                if [ $Lang == "fr" ]
                        then echo "Votre architecture matérielle doit être en 64bits"
                        else echo "You hardware architecture must be 64bits"
                fi
                exit 1
        fi
        IFS="$old"
        if [[ ( $unknown_os != 3 ) || ("$DISTRIBUTION" != "Mageia" ) || ( "$CURRENT_VERSION" != "7" ) ]]
        then
                if [ -e /var/tmp/alcasar-conf.tar.gz ] # update
                        then
                        echo
                        if [ $Lang == "fr" ]
                                then
                                echo "La mise à jour automatique d'ALCASAR ne peut pas être réalisée."
                                echo "1 - Effectuez une sauvegarde des fichiers de traçabilité et de la base des usagers via l'ACC"
                                echo "2 - Installez Linux-Mageia 7.1 (64bits) et ALCASAR (cf. doc d'installation)"
                                echo "3 - Importez votre base des usagers"
                        else
                                echo "The automatic update of ALCASAR can't be performed."
                                echo "1 - Save your traceability files and the user database"
                                echo "2 - Install Linux-Mageia 7.1 (64bits) & ALCASAR (cf. installation doc)"
                                echo "3 - Import your users database"
                        fi
                else
                        if [ $Lang == "fr" ]
                                then echo "L'installation d'ALCASAR ne peut pas être réalisée."
                                else echo "The installation of ALCASAR can't be performed."
                        fi
                fi
                echo
                if [ $Lang == "fr" ]
                        then echo "Le système d'exploitation doit être remplacé (Mageia7.1-64bits)"
                        else echo "The OS must be replaced (Mageia7.1-64bits)"
                fi
                exit 1
        fi

# Test if ALCASAR is already installed
        if [ -e $CONF_FILE ]
        then
                current_version=`grep ^VERSION= $CONF_FILE | cut -d"=" -f2`
                if [ $Lang == "fr" ]
                        then echo "La version $current_version d'ALCASAR est déjà installée"
                        else echo "ALCASAR version $current_version is already installed"
                fi
                response=0
                PTN='^[12]$'
                until [[ "$response" =~ $PTN ]]
                do
                        if [ $Lang == "fr" ]
                                then echo -n "Tapez '1' pour une mise à jour; Tapez '2' pour une réinstallation : "
                                else echo -n "Hit '1' for an update; Hit '2' for a reinstallation : "
                        fi
                        read response
                done
                if [ "$response" = "2" ]
                then
                        rm -f /var/tmp/alcasar-conf*
                else
# Create the archive of conf files
                        $DIR_SCRIPTS/alcasar-conf.sh --create
# avoid lack of local DNS resolution when unbound is updated (alcasar <= V5.3)
                        local_unbound_unit=`ls /etc/systemd/system/unbound* 2>/dev/null | wc -w`
                        if [ $local_unbound_unit -ne 4 ]; then
                                cp -f /lib/systemd/system/unbound*.service /etc/systemd/system/
                        fi
                        mode="update"
                fi
        fi
# Free /var (when updating) and test free space
        [ -d /var/log/netflow ] && rm -rf /var/log/netflow  # remove old porttracker RRD database
        [ -d /var/lib/clamav ] && rm -rf /var/lib/clamav/* # remove old clamav database
        journalctl -q --vacuum-files 1  # remove previous journal logs
        free_space=`df -BG --output=avail /var|tail -1|tr -d '[:space:]G'`
        if [ $free_space -lt 10 ]
                then
                if [ $Lang == "fr" ]
                        then echo "Espace disponible insuffisant sur /var ($free_space Go au lieu de 10 Go au minimum)"
                        else echo "not enough free space on /var ($free_space GB instead of at least 10 GB)"
                fi
        exit 0
        fi
} # End of system_testing

########################################################
##                   "network_testing"                ##
## - Internet access test                             ##
########################################################
network_testing()
{
# Detect external/internal interfaces
        if [ -z "$EXTIF" ]; then
                EXTIF=$(/usr/sbin/ip route list | awk '/ via / {print $5}' | uniq)
                if [ -z "$EXTIF" ]; then
                        if [ "$Lang" == 'fr' ]
                                then echo "Aucune passerelle par défaut configurée"
                                else echo "No default gateway configured"
                        fi
                        exit 1
                fi
        fi
        if [ "$Lang" == 'fr' ]
                then echo "Interface externe (Internet) utilisée : $EXTIF"
                else echo "External interface (Internet) used: $EXTIF"
        fi

        if [ -z "$INTIF" ]; then
                interfacesList=$(/usr/sbin/ip -br link show | cut -d' ' -f1 | grep -v "^\(lo\|tun0\|$EXTIF\)\$")
                interfacesCount=$(echo "$interfacesList" | wc -w)
                if [ $interfacesCount -eq 0 ]; then
                        if [ "$Lang" == 'fr' ]
                                then echo "Aucune interface de disponible pour le réseau interne"
                                else echo "No interface available for the internal network"
                        fi
                        exit 1
                elif [ $interfacesCount -eq 1 ]; then
                        INTIF="$interfacesList"
                else
                        interfacesSorted=$(/usr/sbin/ip -br addr | grep -v "^\(lo\|tun0\|$EXTIF\) " | sort -b -k3n -k2r -k1)
                        interfacePreferred=$(echo "$interfacesSorted" | head -1 | cut -d' ' -f1)
                        if [ "$Lang" == 'fr' ]
                                then echo 'Liste des interfaces disponible :'
                                else echo 'List of available interfaces:'
                        fi
                        echo "$interfacesSorted"
                        response=''
                        while true; do
                                if [ "$Lang" == 'fr' ]
                                        then echo -n "Choix de l'interface interne ? [$interfacePreferred] "
                                        else echo -n "Choice of internal interface ? [$interfacePreferred] "
                                fi
                                read response

                                [ -z "$response" ] && response="$interfacePreferred"

                                # Check if interface exist
                                if [ "$(echo "$interfacesList" | grep -c "^$response\$")" -eq 1 ]; then
                                        INTIF="$response"
                                        break
                                else
                                        if [ "$Lang" == 'fr' ]
                                                then echo "Interface \"$response\" introuvable"
                                                else echo "Interface \"$response\" not found"
                                        fi
                                fi
                        done
                fi
        fi
        if [ "$Lang" == 'fr' ]
                then echo "Interface interne utilisée : $INTIF"
                else echo "Internal interface used: $INTIF"
        fi

        if [ $Lang == "fr" ]
                then echo -n "Tests des paramètres réseau : "
                else echo -n "Network parameters tests: "
        fi
# Remove conf file if NIC is not plugged (ie : GSM/WIFI/Bt dongles)
        cd /etc/sysconfig/network-scripts/ || { echo "Unable to find /etc/sysconfig/network-scripts directory"; exit 1; }
        IF_INTERFACES=`ls ifcfg-*|cut -d"-" -f2|grep -v "^lo"|cut -d"*" -f1`
        for i in $IF_INTERFACES
        do
                if [ "$(/usr/sbin/ip link | grep -c " $i:")" -eq 0 ]; then
                        rm -f ifcfg-$i

                        if [ $Lang == "fr" ]
                                then echo "Suppression : ifcfg-$i"
                                else echo "Deleting: ifcfg-$i"
                        fi
                fi
        done
        cd $DIR_INSTALL || { echo "Unable to find $DIR_INSTALL directory"; exit 1; }
        echo -n "."
# Test Ethernet NIC links state
        interfacesDown=$(/usr/sbin/ip -br link | grep "^\($EXTIF\|$INTIF\) " | grep 'NO-CARRIER' | cut -d' ' -f1)
        if [ ! -z "$interfacesDown" ]; then
                for i in $interfacesDown; do
                        if [ $Lang == "fr" ]
                        then
                                echo -e "\nÉchec"
                                echo "Le lien réseau de la carte $i n'est pas actif."
                                echo "Assurez-vous que cette carte est bien connectée à un équipement (commutateur, A.P., etc.)"
                        else
                                echo -e "\nFailed"
                                echo "The link state of $i interface is down."
                                echo "Make sure that this network card is connected to a switch or an A.P."
                        fi
                done
                exit 1
        fi
        echo -n "."
# Test EXTIF config files
        PUBLIC_IP_MASK=`/usr/sbin/ip addr show $EXTIF | grep '^\s*inet\s' | awk '{ print $2 }'`
        PUBLIC_IP=`echo $PUBLIC_IP_MASK | cut -d'/' -f1`
        PUBLIC_GATEWAY=`/usr/sbin/ip route list | awk -v EXTIF="$EXTIF" '(/ via / && $5 == EXTIF) {print $3}' | head -n 1`
        if [ "$(echo $PUBLIC_IP|wc -c)" -lt 7 ] || [ "$(echo $PUBLIC_GATEWAY|wc -c)" -lt 7 ]
        then
                if [ $Lang == "fr" ]
                then
                        echo -e "\nÉchec"
                        echo "La carte réseau connectée à Internet ($EXTIF) n'est pas correctement configurée."
                        echo "Renseignez les champs suivants dans le fichier '/etc/sysconfig/network-scripts/ifcfg-$EXTIF' :"
                        echo "Appliquez les changements : 'systemctl restart network'"
                else
                        echo -e "\nFailed"
                        echo "The Internet connected network card ($EXTIF) isn't well configured."
                        echo "The folowing parametres must be set in the file '/etc/sysconfig/network-scripts/ifcfg-$EXTIF' :"
                        echo "Apply the new configuration: 'systemctl restart network'"
                fi
                echo "DEVICE=$EXTIF"
                echo "IPADDR="
                echo "NETMASK="
                echo "GATEWAY="
                echo "DNS1="
                echo "DNS2="
                echo "ONBOOT=yes"
                exit 1
        fi
        echo -n "."
# Test if default GW is alive
        arp_reply=`/usr/sbin/arping -b -I$EXTIF -c1 -w2 $PUBLIC_GATEWAY|grep response|cut -d" " -f2`
        if [ "$(expr $arp_reply)" -eq 0 ]
                then
                if [ $Lang == "fr" ]
                then
                        echo -e "\nÉchec"
                        echo "Le routeur de sortie ou la Box Internet ($PUBLIC_GATEWAY) ne répond pas."
                        echo "Réglez ce problème puis relancez ce script."
                else
                        echo -e "\nFailed"
                        echo "The Internet gateway or the ISP equipment ($PUBLIC_GATEWAY) doesn't answered."
                        echo "Resolv this problem, then restart this script."
                fi
                exit 1
        fi
        echo -n "."
# Test Internet connectivity
        domainTested='www.google.com'
        /usr/bin/curl -s --head "$domainTested" &>/dev/null
        if [ $? -ne 0 ]; then
                if [ $Lang == "fr" ]
                then
                        echo -e "\nLa tentative de connexion vers Internet a échoué ($domainTested)."
                        echo "Vérifiez que la carte $EXTIF est bien connectée au routeur du FAI."
                        echo "Vérifiez la validité des adresses IP des DNS."
                else
                        echo -e "\nThe Internet connection try failed ($domainTested)."
                        echo "Please, verify that the $EXTIF card is connected with the Internet gateway."
                        echo "Verify the DNS IP addresses"
                fi
                exit 1
        fi
        echo ". : ok"
} # End of network_testing()

#######################################################################
##                             "init"                                ##
## - Creation of ALCASAR conf file "/usr/local/etc/alcasar.conf      ##
## - Creation of random password for GRUB, mariadb (admin and user)  ##
#######################################################################
init()
{
        if [ "$mode" != "update" ]
        then
# On affecte le nom d'organisme
                header_install
                ORGANISME=!
                PTN='^[a-zA-Z0-9-]*$'
                until [[ "$ORGANISME" =~ $PTN ]]
                do
                        if [ $Lang == "fr" ]
                                then echo -n "Entrez le nom de votre organisme : "
                                else echo -n "Enter the name of your organism : "
                        fi
                        read ORGANISME
                        if [ "$ORGANISME" == "" ]
                        then
                                ORGANISME=!
                        fi
                done
        fi
# On crée aléatoirement les mots de passe et les secrets partagés
# We create random passwords and shared secrets
        rm -f $PASSWD_FILE
        echo "#####  ALCASAR ($ORGANISME) security passwords  #####" > $PASSWD_FILE
        grub2pwd=`cat /dev/urandom | tr -dc '[:alnum:]' | head -c8`
        pbkdf2=`( echo $grub2pwd ; echo $grub2pwd ) | \
                LC_ALL=C /usr/bin/grub2-mkpasswd-pbkdf2 | \
                grep -v '[eE]nter password:' | \
                sed -e "s/PBKDF2 hash of your password is //"`
        echo "GRUB2_PASSWORD=$pbkdf2" > /boot/grub2/user.cfg
        [ -e /root/grub.default ] || cp /etc/grub.d/10_linux /root/grub.default
        cp -f $DIR_CONF/grub-10_linux /etc/grub.d/10_linux  # Request password only on menu editing attempts (not when selecting an entry)
        chmod 0600 /boot/grub2/user.cfg
        echo "# Login name and password to protect GRUB2 boot menu (!!!qwerty keyboard) : " > $PASSWD_FILE
        echo "GRUB2_user=root" >> $PASSWD_FILE
        echo "GRUB2_password=$grub2pwd" >> $PASSWD_FILE
        mysqlpwd=`cat /dev/urandom | tr -dc '[:alnum:]' | head -c16`
        echo "# Login name and Password of MariaDB administrator:" >> $PASSWD_FILE
        echo "db_root=$mysqlpwd" >> $PASSWD_FILE
        radiuspwd=`cat /dev/urandom | tr -dc '[:alnum:]' | head -c16`
        echo "# Login name and password of MariaDB user:" >> $PASSWD_FILE
        echo "db_user=$DB_USER" >> $PASSWD_FILE
        echo "db_password=$radiuspwd" >> $PASSWD_FILE
        secretuam=`cat /dev/urandom | tr -dc '[:alnum:]' | head -c16`
        echo "# Shared secret between the script 'intercept.php' and coova-chilli:" >> $PASSWD_FILE
        echo "secret_uam=$secretuam" >> $PASSWD_FILE
        secretradius=`cat /dev/urandom | tr -dc '[:alnum:]' | head -c16`
        echo "# Shared secret between coova-chilli and FreeRadius:" >> $PASSWD_FILE
        echo "secret_radius=$secretradius" >> $PASSWD_FILE
        chmod 640 $PASSWD_FILE
#  copy scripts in in /usr/local/bin
        cp -fr $DIR_SCRIPTS/alcasar* $DIR_DEST_BIN/. ; chown -R root:root $DIR_DEST_BIN/alcasar* ; chmod -R 740 $DIR_DEST_BIN/alcasar*
#  copy conf files in /usr/local/etc
        cp -f $DIR_CONF/etc/alcasar* $DIR_DEST_ETC/. ; chown -R root:apache $DIR_DEST_ETC ; chmod 770 $DIR_DEST_ETC ; chmod 660 $DIR_DEST_ETC/alcasar*
        $SED "s?^DB_RADIUS=.*?DB_RADIUS=\"$DB_RADIUS\"?g" $DIR_DEST_BIN/alcasar-mysql.sh
# generate central conf file
        cat <<EOF > $CONF_FILE
##########################################
##                                      ##
##          ALCASAR Parameters          ##
##                                      ##
##########################################

INSTALL_DATE=$DATE
VERSION=$VERSION
ORGANISM=$ORGANISME
EOF
        chmod o-rwx $CONF_FILE
} # End of init()

#########################################################
##                     "network"                       ##
## - Define the several network address                ##
## - Define the DNS naming                             ##
## - INTIF parameters (consultation network)           ##
## - Write "/etc/hosts" file                           ##
## - write "hosts.allow" & "hosts.deny" files          ##
#########################################################
network()
{
        header_install
        if [ "$mode" != "update" ]
                then
                if [ $Lang == "fr" ]
                        then echo "Par défaut, l'adresse IP d'ALCASAR sur le réseau de consultation est : $DEFAULT_PRIVATE_IP_MASK"
                        else echo "The default ALCASAR IP address on consultation network is : $DEFAULT_PRIVATE_IP_MASK"
                fi
                response=0
                PTN='^[oOyYnN]?$'
                until [[ "$response" =~ $PTN ]]
                do
                        if [ $Lang == "fr" ]
                                then echo -n "Voulez-vous utiliser cette adresse et ce plan d'adressage (recommandé) (O/n)? : "
                                else echo -n "Do you want to use this IP address and this IP addressing plan (recommanded) (Y/n)? : "
                        fi
                        read response
                done
                if [ "$response" = "n" ] || [ "$response" = "N" ]
                then
                        PRIVATE_IP_MASK="0"
                        PTN='^\([01]\?[[:digit:]][[:digit:]]\?\|2[0-4][[:digit:]]\|25[0-5]\).\([01]\?[[:digit:]][[:digit:]]\?\|2[0-4][[:digit:]]\|25[0-5]\).\([01]\?[[:digit:]][[:digit:]]\?\|2[0-4][[:digit:]]\|25[0-5]\).\([01]\?[[:digit:]][[:digit:]]\?\|2[0-4][[:digit:]]\|25[0-5]\)/[012]\?[[:digit:]]$'
                        until [[ $(expr "$PRIVATE_IP_MASK" : $PTN) -gt 0 ]]
                        do
                                if [ $Lang == "fr" ]
                                        then echo -n "Entrez l'adresse IP d'ALCASAR au format CIDR (a.b.c.d/xx) : "
                                        else echo -n "Enter ALCASAR IP address in CIDR format (a.b.c.d/xx) : "
                                fi
                                read PRIVATE_IP_MASK
                        done
                else
                        PRIVATE_IP_MASK=$DEFAULT_PRIVATE_IP_MASK
                fi
        else
                PRIVATE_IP_MASK=`grep ^PRIVATE_IP= /var/tmp/conf/etc/alcasar.conf|cut -d"=" -f2`
                rm -rf /var/tmp/conf
        fi
# Define LAN side global parameters
        hostnamectl set-hostname $HOSTNAME.$DOMAIN
        PRIVATE_NETWORK=`/bin/ipcalc -n $PRIVATE_IP_MASK | cut -d"=" -f2`                               # private network address (ie.: 192.168.182.0)
        private_network_ending=`echo $PRIVATE_NETWORK | cut -d"." -f4`                                  # last octet of LAN address
        PRIVATE_NETMASK=`/bin/ipcalc -m $PRIVATE_IP_MASK | cut -d"=" -f2`                               # private network mask (ie.: 255.255.255.0)
        PRIVATE_PREFIX=`/bin/ipcalc -p $PRIVATE_IP_MASK |cut -d"=" -f2`                                 # network prefix (ie. 24)
        PRIVATE_IP=`echo $PRIVATE_IP_MASK | cut -d"/" -f1`                                              # ALCASAR private ip address (consultation LAN side)
        if [ $PRIVATE_IP == $PRIVATE_NETWORK ]                                                          # when entering network address instead of ip address
        then
                PRIVATE_IP=`echo $PRIVATE_NETWORK | cut -d"." -f1-3`"."`expr $private_network_ending + 1`
                PRIVATE_IP_MASK=`echo $PRIVATE_IP/$PRIVATE_PREFIX`
        fi
        private_ip_ending=`echo $PRIVATE_IP | cut -d"." -f4`                                            # last octet of LAN address
        PRIVATE_SECOND_IP=`echo $PRIVATE_IP | cut -d"." -f1-3`"."`expr $private_ip_ending + 1`          # second network address (ex.: 192.168.182.2)
        PRIVATE_NETWORK_MASK=$PRIVATE_NETWORK/$PRIVATE_PREFIX                                           # ie.: 192.168.182.0/24
        classe=$((PRIVATE_PREFIX/8))                                                                    # ie.: 2=classe B, 3=classe C
        PRIVATE_NETWORK_SHORT=`echo $PRIVATE_NETWORK | cut -d"." -f1-$classe`.                          # compatibility with hosts.allow et hosts.deny (ie.: 192.168.182.)
        PRIVATE_MAC=`/usr/sbin/ip link show $INTIF | grep ether | cut -d" " -f6| sed 's/:/-/g'| awk '{print toupper($0)}'`      # MAC address of INTIF
# Define Internet parameters
        DNS1=`cat /etc/sysconfig/network-scripts/ifcfg-$EXTIF | grep '^DNS1='| cut -d"=" -f2`   # 1st DNS server
        DNS2=`cat /etc/sysconfig/network-scripts/ifcfg-$EXTIF | grep '^DNS2=' | cut -d"=" -f2`  # 2nd DNS server
        DNS1=${DNS1:=208.67.220.220}
        DNS2=${DNS2:=208.67.222.222}
        PUBLIC_NETMASK=`/bin/ipcalc -m $PUBLIC_IP_MASK | cut -d"=" -f2`
        PUBLIC_PREFIX=`/bin/ipcalc -p $PUBLIC_IP $PUBLIC_NETMASK|cut -d"=" -f2`
        PUBLIC_NETWORK=`/bin/ipcalc -n $PUBLIC_IP/$PUBLIC_PREFIX|cut -d"=" -f2`
# Write network parameters in the conf file
        echo "HOSTNAME=$HOSTNAME" >> $CONF_FILE
        echo "DOMAIN=$DOMAIN" >> $CONF_FILE
        echo "EXTIF=$EXTIF" >> $CONF_FILE
        echo "INTIF=$INTIF" >> $CONF_FILE
# Retrieve NIC name of other consultation LAN
        INTERFACES=`/usr/sbin/ip link|grep '^[[:digit:]]:'|grep -v "^lo\|$EXTIF\|tun0"|cut -d " " -f2|tr -d ":"`
        for i in $INTERFACES
        do
                SUB=`echo ${i:0:2}`
                if [ $SUB = "wl" ]
                        then WIFIF=$i
                elif [ "$i" != "$INTIF" ] && [ $SUB != "ww" ]
                        then LANIF=$i
                fi
        done
        if [ -n "$WIFIF" ]
                then echo "WIFIF=$WIFIF" >> $CONF_FILE
        elif [ -n "$LANIF" ]
                then echo "LANIF=$LANIF" >> $CONF_FILE
        fi
        IP_SETTING=`grep BOOTPROTO /etc/sysconfig/network-scripts/ifcfg-$EXTIF|cut -d"=" -f2` # test static or dynamic
        if [ $IP_SETTING == "dhcp" ]
        then
                DHCP_DNS_servers=`cat /var/lib/dhclient/dhclient--$EXTIF.lease |grep domain-name-servers|sed -n "1 p"| rev|cut -d" " -f1|rev|tr -d ';'`
                DNS1=`echo $DHCP_DNS_servers | cut -d"," -f1`
                DNS2=`echo $DHCP_DNS_servers | cut -d"," -f2`
                echo "PUBLIC_IP=dhcp" >> $CONF_FILE
                echo "GW=dhcp" >> $CONF_FILE
        else
                echo "PUBLIC_IP=$PUBLIC_IP/$PUBLIC_PREFIX" >> $CONF_FILE
                echo "GW=$PUBLIC_GATEWAY" >> $CONF_FILE
        fi
        echo "DNS1=$DNS1" >> $CONF_FILE
        echo "DNS2=$DNS2" >> $CONF_FILE
        echo "PROXY=off" >> $CONF_FILE
        echo "PROXY_IP=\"192.168.0.100:80\"" >> $CONF_FILE
        echo "PUBLIC_WEIGHT=1" >> $CONF_FILE
        echo "PUBLIC_MTU=$MTU" >> $CONF_FILE
        echo "PRIVATE_IP=$PRIVATE_IP_MASK" >> $CONF_FILE
        echo "DHCP=on" >> $CONF_FILE
        echo "EXT_DHCP_IP=" >> $CONF_FILE
        echo "RELAY_DHCP_IP=" >> $CONF_FILE
        echo "RELAY_DHCP_PORT=" >> $CONF_FILE
        echo "INT_DNS_DOMAIN=" >> $CONF_FILE
        echo "INT_DNS_IP=" >> $CONF_FILE
        echo "INT_DNS_ACTIVE=off" >> $CONF_FILE
# network default
        [ -e /etc/sysconfig/network.default ] || cp /etc/sysconfig/network /etc/sysconfig/network.default
        cat <<EOF > /etc/sysconfig/network
NETWORKING=yes
FORWARD_IPV4=true
EOF
# write "/etc/hosts"
        [ -e /etc/hosts.default ] || cp /etc/hosts /etc/hosts.default
        cat <<EOF > /etc/hosts
127.0.0.1       localhost
$PRIVATE_IP     $HOSTNAME
EOF
# write EXTIF (Internet) config
        [ -e /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF ] || cp /etc/sysconfig/network-scripts/ifcfg-$EXTIF /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF
        if [ $IP_SETTING == "dhcp" ]
        then
                cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$EXTIF
DEVICE=$EXTIF
BOOTPROTO=dhcp
DNS1=127.0.0.1
PEERDNS=no
RESOLV_MODS=yes
ONBOOT=yes
NOZEROCONF=yes
METRIC=10
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
MTU=$MTU
EOF
        else
                cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$EXTIF
DEVICE=$EXTIF
BOOTPROTO=static
IPADDR=$PUBLIC_IP
NETMASK=$PUBLIC_NETMASK
GATEWAY=$PUBLIC_GATEWAY
DNS1=$DNS1
DNS2=$DNS2
RESOLV_MODS=yes
ONBOOT=yes
METRIC=10
NOZEROCONF=yes
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
MTU=$MTU
EOF
        fi
# write INTIF (consultation LAN) in normal mode
cp -f /etc/sysconfig/network-scripts/ifcfg-$INTIF /etc/sysconfig/network-scripts/default-ifcfg-$INTIF
        cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$INTIF
DEVICE=$INTIF
BOOTPROTO=static
ONBOOT=yes
NOZEROCONF=yes
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
EOF
# write INTIF in bypass mode (see "alcasar-bypass.sh")
        cat <<EOF > /etc/sysconfig/network-scripts/bypass-ifcfg-$INTIF
DEVICE=$INTIF
BOOTPROTO=static
IPADDR=$PRIVATE_IP
NETMASK=$PRIVATE_NETMASK
ONBOOT=yes
METRIC=10
NOZEROCONF=yes
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
EOF
######### Config WIFIF (consultation WIFI) ou LANIF (consultation LAN) in normal mode #################
        if [ -n "$WIFIF" ] && [ "$WIFIF" != "$INTIF" ]
        then
                cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$WIFIF
DEVICE=$WIFIF
BOOTPROTO=static
ONBOOT=yes
NOZEROCONF=yes
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
EOF
        elif [ -n "$LANIF" ]
        then
                cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$LANIF
DEVICE=$LANIF
BOOTPROTO=static
ONBOOT=yes
NOZEROCONF=yes
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
EOF
        fi
# write hosts.allow & hosts.deny
        [ -e /etc/hosts.allow.default ]  || cp /etc/hosts.allow /etc/hosts.allow.default
        cat <<EOF > /etc/hosts.allow
ALL: LOCAL, 127.0.0.1, localhost, $PRIVATE_IP
sshd: ALL
ntpd: $PRIVATE_NETWORK_SHORT
EOF
        [ -e /etc/host.deny.default ]  || cp /etc/hosts.deny /etc/hosts.deny.default
        cat <<EOF > /etc/hosts.deny
ALL: ALL: spawn ( /bin/echo "service %d demandé par %c" | /bin/mail -s "Tentative d'accès au service %d par %c REFUSE !!!" security ) &
EOF
        chmod o+r $DIR_DEST_BIN/alcasar-iptables.sh #lecture possible pour apache (interface php du filtrage réseau)
# create the ip_blocked file with a first line (LAN between ALCASAR and the Internet GW)
        echo "#$PUBLIC_NETWORK/$PUBLIC_PREFIX LAN-ALCASAR-BOX" > $DIR_DEST_ETC/alcasar-ip-blocked
# load conntrack ftp module
        [ -e /etc/modprobe.preload.default ] || cp /etc/modprobe.preload /etc/modprobe.preload.default
        echo "nf_conntrack_ftp" >>  /etc/modprobe.preload
# load ipt_NETFLOW module
        echo "ipt_NETFLOW" >>  /etc/modprobe.preload
# modify iptables service files (start with "alcasar-iptables.sh" and stop with flush)
        cp /lib/systemd/system/iptables.service /etc/systemd/system/iptables.service
        $SED 's/ExecStart=\/usr\/libexec\/iptables.init start/ExecStart=\/usr\/local\/bin\/alcasar-iptables.sh/' /etc/systemd/system/iptables.service
        [ -e /usr/libexec/iptables.init.default ] || cp /usr/libexec/iptables.init /usr/libexec/iptables.init.default
        $SED "s?\[ -f \$IPTABLES_CONFIG \] .*?#&?" /usr/libexec/iptables.init # comment the test (flush all rules & policies)
# create the alcasar-network unit
        cat << EOF > /etc/systemd/system/alcasar-network.service
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.

# This unit starts alcasar-network.sh script.
[Unit]
Description=alcasar-network.sh execution
After=network.target iptables.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=$DIR_DEST_BIN/alcasar-network.sh
ExecStop=$DIR_DEST_BIN/alcasar-network.sh
TimeoutSec=0

[Install]
WantedBy=multi-user.target
EOF
        /usr/bin/systemctl daemon-reload

# the script "$DIR_DEST_BIN/alcasar-iptables.sh" is started at the end of this script in order not to cut network flow in case of using ssh
} # End of network()

##################################################################
##                           "CA"                               ##
## - Creating the CA and the server certificate (lighttpd)      ##
##################################################################
CA()
{
        $DIR_DEST_BIN/alcasar-CA.sh
        chmod 755 /etc/pki/
        chown root:apache /etc/pki/CA; chmod 750 /etc/pki/CA
        chown root:apache /etc/pki/CA/alcasar-ca.crt; chmod 640 /etc/pki/CA/alcasar-ca.crt
        chown root:root /etc/pki/CA/private; chmod 700 /etc/pki/CA/private
        chmod 600 /etc/pki/CA/private/*
        chown -R root:apache /etc/pki/tls/private; chmod 750 /etc/pki/tls/private
        chmod 640 /etc/pki/tls/private/*
        chmod 644 /etc/pki/tls/certs/* # "freshclam" need to access to that bundle
} # End of CA()

######################################################
##                       "ACC"                      ##
## - copy ALCASAR Control Center (ACC) files        ##
## - configuration of the web server (Lighttpd)     ##
## - creation of the first ACC admin account        ##
## - secure the ACC access                          ##
######################################################
ACC()
{
        [ -d $DIR_WEB ] && rm -rf $DIR_WEB
        mkdir $DIR_WEB
# Copy & adapt ACC files
        cp -rf $DIR_INSTALL/web/* $DIR_WEB/
        $SED "s?99/99/9999?$DATE_SHORT?g" $DIR_ACC/menu.php
        $SED "s?\$DB_RADIUS = .*?\$DB_RADIUS = \"$DB_RADIUS\"\;?g" $DIR_ACC/welcome.php
        $SED "s?\$DB_USER = .*?\$DB_USER = \"$DB_USER\"\;?g" $DIR_ACC/welcome.php
        $SED "s?\$radiuspwd = .*?\$radiuspwd = \"$radiuspwd\"\;?g" $DIR_ACC/welcome.php
        chown -R apache:apache $DIR_WEB/*
# copy & adapt "freeradius-web" files
        cp -rf $DIR_CONF/freeradius-web/ /etc/
        [ -e /etc/freeradius-web/admin.conf.default ] || cp /etc/freeradius-web/admin.conf /etc/freeradius-web/admin.conf.default
        $SED "s?^general_domain:.*?general_domain: $DOMAIN?g" /etc/freeradius-web/admin.conf
        $SED "s?^sql_username:.*?sql_username: $DB_USER?g" /etc/freeradius-web/admin.conf
        $SED "s?^sql_password:.*?sql_password: $radiuspwd?g" /etc/freeradius-web/admin.conf
        cat <<EOF > /etc/freeradius-web/naslist.conf
nas1_name: alcasar-$ORGANISME
nas1_model: Network Access Controler
nas1_ip: $PRIVATE_IP
nas1_port_num: 0
nas1_community: public
EOF
        chown -R apache:apache /etc/freeradius-web/
# create the log & backup structure :
# - base = users database
# - archive = tarball of "base + http firewall + netflow"
# - security = watchdog log
# - conf_file = archive conf file (usefull in updating process)
        for i in base archive security activity_report iot_captures;
        do
                [ -d $DIR_SAVE/$i ] || mkdir -p $DIR_SAVE/$i
        done
        chown -R root:apache $DIR_SAVE
# Configuring & securing php
        [ -e /etc/php.d/05_date.ini.default ] || cp /etc/php.d/05_date.ini /etc/php.d/05_date.ini.default
        timezone=`timedatectl show --property=Timezone|cut -d"=" -f2`
        $SED "s?^;date.timezone =.*?date.timezone = $timezone?g" /etc/php.d/05_date.ini
        [ -e /etc/php.ini.default ] || cp /etc/php.ini /etc/php.ini.default
        $SED "s?^upload_max_filesize.*?upload_max_filesize = 100M?g" /etc/php.ini
        $SED "s?^post_max_size.*?post_max_size = 100M?g" /etc/php.ini
        $SED "s?^display_errors.*?display_errors = Off?" /etc/php.ini
        $SED "s?^display_startup_errors.*?display_startup_errors = Off?" /etc/php.ini
        $SED "s?^html_errors.*?html_errors = Off?g" /etc/php.ini
        $SED "s?^expose_php.*?expose_php = Off?g" /etc/php.ini
        $SED "s?^allow_url_fopen.*?allow_url_fopen = Off?" /etc/php.ini
# Configuring & securing Lighttpd
        rm -rf /var/www/cgi-bin/* /var/www/perl/* /var/www/icons/README* /var/www/error/README*
        [ -e /etc/lighttpd/lighttpd.conf.default ] || cp /etc/lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf.default
        $SED "s?^server\.use-ipv6.*?server\.use-ipv6 = \"disable\"?g" /etc/lighttpd/lighttpd.conf
        $SED "s?^#server\.bind.*?server\.bind = \"$PRIVATE_IP\"?g" /etc/lighttpd/lighttpd.conf
        $SED "s?^server\.bind.*?server\.bind = \"$PRIVATE_IP\"?g" /etc/lighttpd/lighttpd.conf
        $SED "s?^#server\.tag.*?server\.tag = \"\"?g" /etc/lighttpd/lighttpd.conf
        echo "include \"vhosts.d/alcasar.conf\"" >> /etc/lighttpd/lighttpd.conf

        [ -e /etc/lighttpd/modules.conf.default ] || cp /etc/lighttpd/modules.conf /etc/lighttpd/modules.conf.default
        $SED "s?^#[ ]*\"mod_auth\",.*?\"mod_auth\",?g" /etc/lighttpd/modules.conf
        $SED "s?^#[ ]*\"mod_alias\",.*?\"mod_alias\",?g" /etc/lighttpd/modules.conf
        $SED "s?^#[ ]*\"mod_redirect\",.*?\"mod_redirect\",?g" /etc/lighttpd/modules.conf
        $SED "/^[ ]*\"mod_redirect\",/a\"mod_openssl\"," /etc/lighttpd/modules.conf
        $SED "s?^#include \"conf.d/fastcgi.conf\".*?include \"conf.d/fastcgi.conf\"?g" /etc/lighttpd/modules.conf

        [ -e /etc/lighttpd/conf.d/fastcgi.conf.default ] || cp /etc/lighttpd/conf.d/fastcgi.conf /etc/lighttpd/conf.d/fastcgi.conf.default
        cp $DIR_CONF/lighttpd/conf.d/fastcgi.conf /etc/lighttpd/conf.d/fastcgi.conf

        [ -e /etc/php-fpm.conf.default ] || cp /etc/php-fpm.conf /etc/php-fpm.conf.default
        $SED "s?^;listen\.owner.*?listen\.owner = apache?g" /etc/php-fpm.conf
        $SED "s?^;listen\.group.*?listen\.group = apache?g" /etc/php-fpm.conf
        $SED "s?^;listen\.mode.*?listen\.mode = 0660?g" /etc/php-fpm.conf

        [ -d /etc/lighttpd/vhosts.d ] || mkdir /etc/lighttpd/vhosts.d
        cp $DIR_CONF/lighttpd/vhosts.d/* /etc/lighttpd/vhosts.d/
        $SED 's/^$SERVER\["socket"\] == ".*:443.*/$SERVER\["socket"\] == "'"$PRIVATE_IP"':443" {/g' /etc/lighttpd/vhosts.d/alcasar-with-ssl.conf /etc/lighttpd/vhosts.d/alcasar-without-ssl.conf
        $SED "s/^\([\t ]*\)var.server_name.*/\1var.server_name = \"$PRIVATE_IP\"/g" /etc/lighttpd/vhosts.d/alcasar-with-ssl.conf /etc/lighttpd/vhosts.d/alcasar-without-ssl.conf
        ln -s /etc/lighttpd/vhosts.d/alcasar-without-ssl.conf /etc/lighttpd/vhosts.d/alcasar.conf

        [ -d /var/log/lighttpd ] || mkdir /var/log/lighttpd
        [ -e /var/log/lighttpd/access.log ] || touch /var/log/lighttpd/access.log
        [ -e /var/log/lighttpd/error.log ] || touch /var/log/lighttpd/error.log

        chown -R apache:apache /var/log/lighttpd

# Creation of the first account (in 'admin' profile)
        if [ "$mode" = "install" ]
        then
                header_install
# Creation of keys file for the admin account ("admin")
                [ -d $DIR_DEST_ETC/digest ] && rm -rf $DIR_DEST_ETC/digest
                mkdir -p $DIR_DEST_ETC/digest
                chmod 755 $DIR_DEST_ETC/digest
                if [ $Lang == "fr" ]
                        then echo "Création du premier compte administrateur : "
                        else echo "Creation of the first admin account : "
                fi
                until [ -s $DIR_DEST_ETC/digest/key_admin ]
                do
                        $DIR_DEST_BIN/alcasar-profil.sh --add admin
                done
        fi
# Creation of ACC certs links
        [ -d /var/www/html/certs ] || mkdir /var/www/html/certs
        ln -s /etc/pki/CA/alcasar-ca.crt /var/www/html/certs/certificat_alcasar_ca.crt
# Run lighttpd after coova (in order waiting tun0 to be up)
        cp /lib/systemd/system/lighttpd.service /etc/systemd/system/lighttpd.service
        $SED "s?^After=.*?After=network.target remote-fs.target nss-lookup.target chilli.service?g" /etc/systemd/system/lighttpd.service
        # Log file for ACC access imputability
        [ -e $DIR_SAVE/security/acc_access.log ] || touch $DIR_SAVE/security/acc_access.log
        chown root:apache $DIR_SAVE/security/acc_access.log
        chmod 664 $DIR_SAVE/security/acc_access.log
# Copy IEEE-MAC-manuf list (origin from sanitized nmac file : see linuxnet.ca)
    cp $DIR_CONF/nmap-mac-prefixes /usr/local/share/
} # End of ACC()

#############################################################
##                     "time_server"                       ##
## - Configuring NTP server                                ##
#############################################################
time_server()
{
# Set the Internet time server
        [ -e /etc/ntp/step-tickers.default ] || cp /etc/ntp/step-tickers /etc/ntp/step-tickers.default
        cat <<EOF > /etc/ntp/step-tickers
0.fr.pool.ntp.org       # adapt to your country
1.fr.pool.ntp.org
2.fr.pool.ntp.org
EOF
        [ -e /etc/ntp.conf.default ] || cp /etc/ntp.conf /etc/ntp.conf.default
        cat <<EOF > /etc/ntp.conf
server 0.fr.pool.ntp.org        # adapt to your country
server 1.fr.pool.ntp.org
server 2.fr.pool.ntp.org
server 127.127.1.0              # local clock si NTP internet indisponible ...
fudge 127.127.1.0 stratum 10
restrict $PRIVATE_NETWORK mask $PRIVATE_NETMASK nomodify notrap
restrict 127.0.0.1
driftfile /var/lib/ntp/drift
logfile /var/log/ntp.log
disable monitor
EOF
        chown -R ntp:ntp /var/lib/ntp
# Synchronize now
        ntpd -4 -q -g &
} # End of time_server()

#####################################################################
##                           "init_db"                             ##
## - Mysql initialization                                          ##
## - Set admin (root) password                                     ##
## - Remove unused users & databases                               ##
## - Radius database creation                                      ##
## - Copy of accounting tables (mtotacct, totacct) & userinfo      ##
#####################################################################
init_db()
{
        if [ "`systemctl is-active mysqld`" == "active" ]
        then
                systemctl stop mysqld
        fi
        rm -rf /var/lib/mysql # to be sure that there is no former installation
        [ -e /etc/my.cnf.default ] || cp /etc/my.cnf /etc/my.cnf.default
        $SED "s?^tmpdir.*?tmpdir=/tmp?g" /etc/my.cnf
        $SED "s?^port.*?#&?g" /etc/my.cnf # we use unix socket only
        $SED "s?^;collation_server =.*?collation_server = utf8_unicode_ci?g" /etc/my.cnf
        $SED "s?^;character_set_server =.*?character_set_server = utf8?g" /etc/my.cnf  # accentuated user names are allowed
        [ -e /etc/my.cnf.d/feedback.cnf ] && $SED "s?^plugin-load.*?#&?g" /etc/my.cnf.d/feedback.cnf # remove the feedback plugin (ALCASAR doesn't report anything !)
        [ -e /etc/my.cnf.d/auth_gssapi.cnf ] && $SED "s?^plugin-load.*?#&?g" /etc/my.cnf.d/auth_gssapi.cnf # remove GSS plugin (ALCASAR doesn't use Kerberos)
        /usr/sbin/mysqld-prepare-db-dir > /dev/null 2>&1
        /usr/bin/systemctl set-environment MYSQLD_OPTS="--skip-grant-tables --skip-networking"
        /usr/bin/systemctl start mysqld
        nb_round=1
        while [ ! -S /var/lib/mysql/mysql.sock ] && [ $nb_round -lt 10 ] # we wait until mariadb is on
        do
                nb_round=`expr $nb_round + 1`
                sleep 2
        done
        if [ ! -S /var/lib/mysql/mysql.sock ]
        then
                echo "Problème : la base données 'MariaDB' ne s'est pas lancée !"
                exit
        fi
# Secure the server
        /usr/bin/mysql --execute "GRANT ALL PRIVILEGES ON *.* TO root@'localhost' IDENTIFIED BY '$mysqlpwd';"
        MYSQL="/usr/bin/mysql -uroot -p$mysqlpwd --execute"
        $MYSQL "DROP DATABASE IF EXISTS test;DROP DATABASE IF EXISTS tmp;"
        $MYSQL "CONNECT mysql;DELETE from user where User='';DELETE FROM user WHERE User='root' AND Host NOT IN ('localhost','127.0.0.1','::1');FLUSH PRIVILEGES;"
# Create 'radius' database
        $MYSQL "CREATE DATABASE IF NOT EXISTS $DB_RADIUS;GRANT ALL ON $DB_RADIUS.* TO $DB_USER@localhost IDENTIFIED BY '$radiuspwd';FLUSH PRIVILEGES;"
# Add an empty radius database structure
        /usr/bin/mysql -u$DB_USER -p$radiuspwd $DB_RADIUS < $DIR_CONF/empty-radiusd-db.sql
# modify the start script in order to close accounting connexion when the system is comming down or up
        cp /lib/systemd/system/mysqld.service /etc/systemd/system/mysqld.service
        $SED "/^ExecStart=/a ExecStop=$DIR_DEST_BIN/alcasar-mysql.sh -acct_stop" /etc/systemd/system/mysqld.service
        $SED "/^ExecStop=/a ExecStartPost=$DIR_DEST_BIN/alcasar-mysql.sh -acct_stop" /etc/systemd/system/mysqld.service
        /usr/bin/systemctl unset-environment MYSQLD_OPTS
        /usr/bin/systemctl daemon-reload
} # End of init_db()

###################################################################
##                           "freeradius"                        ##
## - Set the configuration files                                 ##
## - Set the shared secret between coova-chilli and freeradius   ##
## - Adapt the Mysql conf file and counters                      ##
###################################################################
freeradius()
{
        cp -f $DIR_CONF/empty-radiusd-db.sql /etc/raddb/
        chown -R radius:radius /etc/raddb
        [ -e /etc/raddb/radiusd.conf.default ] || cp /etc/raddb/radiusd.conf /etc/raddb/radiusd.conf.default
# Set radius global parameters (radius.conf)
        $SED "s?^[\t ]*#[\t ]*user =.*?user = radius?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*#[\t ]*group =.*?group = radius?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*status_server =.*?status_server = no?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*proxy_requests.*?proxy_requests = no?g" /etc/raddb/radiusd.conf # remove the proxy function
        $SED "s?^[\t ]*\$INCLUDE proxy.conf.*?#\$INCLUDE proxy.conf?g" /etc/raddb/radiusd.conf # remove the proxy function
# Add ALCASAR & Coovachilli dictionaries
        [ -e /etc/raddb/dictionary.default ] || cp /etc/raddb/dictionary /etc/raddb/dictionary.default
        cp $DIR_CONF/radius/dictionary.alcasar /etc/raddb/
        echo '$INCLUDE dictionary.alcasar' > /etc/raddb/dictionary
        cp /usr/share/doc/coova-chilli/dictionary.coovachilli /etc/raddb/
        echo '$INCLUDE dictionary.coovachilli' >> /etc/raddb/dictionary
# Set "client.conf" to describe radius clients (coova on 127.0.0.1)
        [ -e /etc/raddb/clients.conf.default ] || cp -f /etc/raddb/clients.conf /etc/raddb/clients.conf.default
        cat << EOF > /etc/raddb/clients.conf
client localhost {
        ipaddr = 127.0.0.1
        secret = $secretradius
        shortname = chilli
        nas_type = other
}
EOF
# Set Virtual server
    # Remvoveing all except "alcasar virtual site")
        # INFO : To enable 802.1X, add the "innser-tunnel" virtual server (link in sites-enabled)  Change the firewall rules to allow "radius" extern connections.
        cp $DIR_CONF/radius/alcasar /etc/raddb/sites-available/alcasar
        cp $DIR_CONF/radius/alcasar-with-ldap /etc/raddb/sites-available/alcasar-with-ldap
        chown radius:apache /etc/raddb/sites-available/alcasar*
        chmod 660 /etc/raddb/sites-available/alcasar*
        rm -f /etc/raddb/sites-enabled/*
        ln -s /etc/raddb/sites-available/alcasar /etc/raddb/sites-enabled/alcasar
# Set modules
        # Add custom LDAP "available module"
        # INFO : To enable 802.1X, add the "eap" module and verify access to the keys (/etc/pki/tls/private/radius.pem). Change the firewall rules to allow "radius" extern connections.
        cp -f $DIR_CONF/radius/ldap-alcasar /etc/raddb/mods-available/
        chown -R radius:radius /etc/raddb/mods-available/ldap-alcasar
        # Set only usefull modules for ALCASAR (! the module 'ldap-alcasar' is enabled only via ACC)
        rm -rf  /etc/raddb/mods-enabled/*
        for mods in sql sqlcounter attr_filter expiration logintime pap expr always
        do
                ln -s /etc/raddb/mods-available/$mods /etc/raddb/mods-enabled/$mods
        done
# Configure SQL module
        [ -e /etc/raddb/mods-available/sql.default ] || cp /etc/raddb/mods-available/sql /etc/raddb/mods-available/sql.default
        $SED "s?^[\t ]*driver =.*?driver = \"rlm_sql_mysql\"?g" /etc/raddb/mods-available/sql
        $SED "s?^[\t ]*dialect =.*?dialect = \"mysql\"?g" /etc/raddb/mods-available/sql
        $SED "s?^[\t ]*radius_db =.*?radius_db = \"$DB_RADIUS\"?g" /etc/raddb/mods-available/sql
        $SED "s?^#[\t ]*server =.*?server = \"localhost\"?g" /etc/raddb/mods-available/sql
        $SED "s?^#[\t ]*port =.*?port = \"3306\"?g" /etc/raddb/mods-available/sql
        $SED "s?^#[\t ]*login =.*?login = \"$DB_USER\"?g" /etc/raddb/mods-available/sql
        $SED "s?^#[\t ]*password =.*?password = \"$radiuspwd\"?g" /etc/raddb/mods-available/sql
        # no TLS encryption on 127.0.0.1
        $SED "s?^[\t ]*ca_file =.*?#&?g" /etc/raddb/mods-available/sql
        $SED "s?^[\t ]*ca_path =.*?#&?g" /etc/raddb/mods-available/sql
        $SED "s?^[\t ]*certificate_file =.*?#&?g" /etc/raddb/mods-available/sql
        $SED "s?^[\t ]*private_key_file =.*?#&?g" /etc/raddb/mods-available/sql
        $SED "s?^[\t ]*cipher =.*?#&?g" /etc/raddb/mods-available/sql
        $SED "s?^[\t ]*tls_required =.*?tls_required = no?g" /etc/raddb/mods-available/sql
# queries.conf modifications : case sensitive for username, check simultaneous use, patch on 'postauth' table, etc.
        [ -e /etc/raddb/mods-config/sql/main/mysql/queries.conf.default ] || cp /etc/raddb/mods-config/sql/main/mysql/queries.conf /etc/raddb/mods-config/sql/main/mysql/queries.conf.default
        cp -f $DIR_CONF/radius/queries.conf /etc/raddb/mods-config/sql/main/mysql/queries.conf
        chown -R radius:radius /etc/raddb/mods-config/sql/main/mysql/queries.conf
# sqlcounter modifications
        [ -e /etc/raddb/mods-available/sqlcounter.default ] || cp /etc/raddb/mods-available/sqlcounter /etc/raddb/mods-available/sqlcounter.default
        cp -f $DIR_CONF/radius/sqlcounter /etc/raddb/mods-available/sqlcounter
        chown -R radius:radius /etc/raddb/mods-available/sqlcounter
# make certain that mysql is up before freeradius start
        cp /lib/systemd/system/radiusd.service /etc/systemd/system/radiusd.service
        $SED "s?^After=.*?After=syslog.target network.target mysqld.service?g" /etc/systemd/system/radiusd.service
        /usr/bin/systemctl daemon-reload
# Allow apache to change some conf files (ie : ldap on/off)
        chgrp apache /etc/raddb /etc/raddb/sites-available /etc/raddb/mods-available
        chmod 750 /etc/raddb /etc/raddb/sites-available /etc/raddb/mods-available
} # End of freeradius()

#############################################################################
##                                "chilli"                                 ##
## - Creation of the conf file and init file (systemd) for coova-chilli    ##
## - Adapt the authentication web page (intercept.php)                     ##
#############################################################################
chilli()
{
# chilli unit for systemd
        cat << EOF > /etc/systemd/system/chilli.service
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.

# This unit launches coova-chilli a captive portal
[Unit]
Description=chilli is a captive portal daemon
After=network.target

[Service]
Type=forking
ExecStart=/usr/libexec/chilli start
ExecStop=/usr/libexec/chilli stop
ExecReload=/usr/libexec/chilli reload
PIDFile=/run/chilli.pid

[Install]
WantedBy=multi-user.target
EOF
# init file creation
        [ -e /etc/init.d/chilli.default ] || mv /etc/init.d/chilli /etc/init.d/chilli.default
        cat <<EOF > /etc/init.d/chilli
#!/bin/sh
#
# chilli CoovaChilli init
#
# chkconfig: 2345 65 35
# description: CoovaChilli
### BEGIN INIT INFO
# Provides:       chilli
# Required-Start: network
# Should-Start:
# Required-Stop:  network
# Should-Stop:
# Default-Start:  2 3 5
# Default-Stop:
# Description:    CoovaChilli access controller
### END INIT INFO

[ -f /usr/sbin/chilli ] || exit 0
. /etc/init.d/functions
CONFIG=/etc/chilli.conf
pidfile=/run/chilli.pid
[ -f \$CONFIG ] || {
        echo "\$CONFIG Not found"
        exit 0
}
current_users_file="/tmp/current_users.txt"     # file containing active users
RETVAL=0
prog="chilli"
case \$1 in
        start)
                if [ -f \$pidfile ] ; then
                        gprintf "chilli is already running"
                else
                        gprintf "Starting \$prog: "
                        echo '' > \$current_users_file && chown root:apache \$current_users_file && chmod 660 \$current_users_file
                        rm -f /run/chilli* # cleaning
                        /usr/sbin/modprobe tun >/dev/null 2>&1
                        echo 1 > /proc/sys/net/ipv4/ip_forward
                        [ -e /dev/net/tun ] || {
                                (cd /dev;
                                mkdir net;
                                cd net;
                                mknod tun c 10 200)
                        }
                        ifconfig $INTIF 0.0.0.0
                        /usr/sbin/ethtool -K $INTIF gro off
                        daemon /usr/sbin/chilli -c \$CONFIG --pidfile=\$pidfile &
                        RETVAL=\$?
                fi
                ;;

        reload)
                killall -HUP chilli
                ;;

        restart)
                \$0 stop
                sleep 2
                \$0 start
                ;;

        status)
                status chilli
                RETVAL=0
                ;;

        stop)
                if [ -f \$pidfile ] ; then
                        gprintf "Shutting down \$prog: "
                        killproc /usr/sbin/chilli
                        RETVAL=\$?
                        [ \$RETVAL = 0 ] && rm -f \$pidfile
                        [ -e \$current_users_file ] && rm -f \$current_users_file
                else
                        gprintf "chilli is not running"
                fi
                ;;

        *)
                echo "Usage: \$0 {start|stop|restart|reload|status}"
                exit 1
esac
echo
EOF
        chmod a+x /etc/init.d/chilli
        ln -s /etc/init.d/chilli /usr/libexec/chilli
# conf file creation
        [ -e /etc/chilli.conf.default ] || cp /etc/chilli.conf /etc/chilli.conf.default
        #NTP Option configuration for DHCP
        #DHCP Options : rfc2132
                #dhcp option value will be convert in hexa.
                #NTP option (or 'option 42') is like :
                #
                #    Code   Len         Address 1               Address 2
                #   +-----+-----+-----+-----+-----+-----+-----+-----+--
                #   |  42 |  n  |  a1 |  a2 |  a3 |  a4 |  a1 |  a2 |  ...
                #   +-----+-----+-----+-----+-----+-----+-----+-----+--
                #
                #Code : 42 => 2a
                #Len : 4 => 04
        PRIVATE_IP_HEXA=$(printf "%02x\n" "$(echo $PRIVATE_IP | cut -d'.' -f1)")$(printf "%02x\n" "$(echo $PRIVATE_IP | cut -d'.' -f2)")$(printf "%02x\n" "$(echo $PRIVATE_IP | cut -d'.' -f3)")$(printf "%02x\n" "$(echo $PRIVATE_IP | cut -d'.' -f4)")
        cat <<EOF > /etc/chilli.conf
# coova config for ALCASAR
cmdsocket       /run/chilli.sock
unixipc         chilli.$INTIF.ipc
pidfile         /run/chilli.pid
net             $PRIVATE_NETWORK_MASK
dhcpif          $INTIF
ethers          $DIR_DEST_ETC/alcasar-ethers
#nodynip
#statip
dynip           $PRIVATE_NETWORK_MASK
domain          $DOMAIN
dns1            $PRIVATE_IP
dns2            $PRIVATE_IP
uamlisten       $PRIVATE_IP
uamport         3990
uamuiport       3991
macauth
macpasswd       password
strictmacauth
locationname    $HOSTNAME.$DOMAIN
radiusserver1   127.0.0.1
radiusserver2   127.0.0.1
radiussecret    $secretradius
radiusauthport  1812
radiusacctport  1813
uamserver       http://$HOSTNAME.$DOMAIN/intercept.php
redirurl
radiusnasid     $HOSTNAME.$DOMAIN
uamsecret       $secretuam
uamallowed      $HOSTNAME,$HOSTNAME.$DOMAIN
coaport         3799
conup           $DIR_DEST_BIN/alcasar-conup.sh
condown         $DIR_DEST_BIN/alcasar-condown.sh
macup           $DIR_DEST_BIN/alcasar-macup.sh
include         $DIR_DEST_ETC/alcasar-uamallowed
include         $DIR_DEST_ETC/alcasar-uamdomain
dhcpopt         2a04$PRIVATE_IP_HEXA
#dhcpgateway            none
#dhcprelayagent         none
#dhcpgatewayport        none
sslkeyfile      /etc/pki/tls/private/alcasar.key
sslcertfile     /etc/pki/tls/certs/alcasar.crt
sslcafile       /etc/pki/tls/certs/server-chain.pem
#redirssl
#uamuissl
EOF
# create files for "DHCP static ip" and "DHCP static ip info". Reserve the second IP address for INTIF (the first one is for tun0)
        echo "$PRIVATE_MAC $PRIVATE_SECOND_IP" > $DIR_DEST_ETC/alcasar-ethers
        echo "$PRIVATE_MAC $PRIVATE_SECOND_IP" > $DIR_DEST_ETC/alcasar-ethers-info
# create files for trusted domains and urls
        touch $DIR_DEST_ETC/alcasar-uamallowed $DIR_DEST_ETC/alcasar-uamdomain
        chown root:apache $DIR_DEST_ETC/alcasar-*
        chmod 660 $DIR_DEST_ETC/alcasar-*
# Configuration des fichier WEB d'interception (secret partagé avec coova-chilli)
        $SED "s?^\$uamsecret =.*?\$uamsecret = \"$secretuam\";?g" $DIR_WEB/intercept.php
# user 'chilli' creation (in order to run conup/off and up/down scripts
        chilli_exist=`grep -c ^chilli: /etc/passwd`
        if [ "$chilli_exist" == "1" ]
        then
                userdel -r chilli 2>/dev/null
        fi
        groupadd -f chilli
        useradd -r -g chilli -s /bin/false -c "system user for coova-chilli" chilli
}  # End of chilli()

################################################################
##                        "e2guardian"                        ##
## - Set the parameters of this HTML proxy (as controler)     ##
################################################################
e2guardian()
{
# Adapt systemd unit
        cp /lib/systemd/system/e2guardian.service /etc/systemd/system/e2guardian.service
        $SED "s?^ExecStart=.*?ExecStart=/usr/sbin/e2guardian -c /etc/e2guardian/e2guardian.conf?g" /etc/systemd/system/e2guardian.service
        $SED "s?^After=.*?After=network.target chilli.service?g" /etc/systemd/system/e2guardian.service
# Adapt the main conf file
        [ -e $DIR_DG/e2guardian.conf.default ] || cp $DIR_DG/e2guardian.conf $DIR_DG/e2guardian.conf.default
# French deny HTML page
        $SED "s?^language =.*?language = 'french'?g" $DIR_DG/e2guardian.conf
# 2 filtergroups (8080 & 8090)
        $SED "s?^filtergroups =.*?filtergroups = 2?g" $DIR_DG/e2guardian.conf
# Listen on 8080 (HTTP for BL users) only on LAN side
        $SED "s?^filterip =.*?filterip = $PRIVATE_IP?g" $DIR_DG/e2guardian.conf
        $SED "s?^filterports =.*?filterports = 8080?g" $DIR_DG/e2guardian.conf
# Listen on 8090 (HTTP for WL/AV users) only on LAN side
        $SED "/^filterip = $PRIVATE_IP/a filterip = $PRIVATE_IP" $DIR_DG/e2guardian.conf
        $SED "/^filterports = 8080/a filterports = 8090" $DIR_DG/e2guardian.conf
# E2guardian doesn't listen transparently on 8443 (HTTPS) (only in future version)
        $SED "s?^transparenthttpsport =.*?#transparenthttpsport = 8443?g" $DIR_DG/e2guardian.conf
# Don't log
        $SED "s?^loglevel =.*?loglevel = 0?g" $DIR_DG/e2guardian.conf
# Disable HTML content control (weighted & banned)
        $SED "s?^weightedphrasemode =.*?weightedphrasemode = 0?g" $DIR_DG/e2guardian.conf
# Enable authport plugin
        $SED "s?^#authplugin = '/etc/e2guardian/authplugins/port.conf'?authplugin = '/etc/e2guardian/authplugins/port.conf'?g" $DIR_DG/e2guardian.conf
        $SED "s?^#mapauthtoports =.*?mapauthtoports = off?g" $DIR_DG/e2guardian.conf
# Enable clamd scanner
        $SED "s?^#contentscanner = '/etc/e2guardian/contentscanners/clamdscan.conf'?contentscanner = '/etc/e2guardian/contentscanners/clamdscan.conf'?g" $DIR_DG/e2guardian.conf

# Adapt the first group conf file
        [ -e $DIR_DG/e2guardianf1.conf.default ] || cp $DIR_DG/e2guardianf1.conf $DIR_DG/e2guardianf1.conf.default
        $SED "s/^reportinglevel =.*/reportinglevel = 3/g" $DIR_DG/e2guardianf1.conf
        $SED "s/^groupname =.*/groupname = 'blacklisted users'/g" $DIR_DG/e2guardianf1.conf
        $SED "s/^#htmltemplate =.*/htmltemplate = 'alcasar-e2g.html'/g" $DIR_DG/e2guardianf1.conf

# copy & adapt HTML templates
        cp $DIR_CONF/alcasar-e2g-fr.html /usr/share/e2guardian/languages/french/alcasar-e2g.html
        cp $DIR_CONF/alcasar-e2g-en.html /usr/share/e2guardian/languages/ukenglish/alcasar-e2g.html
        $SED "s?\/\/[a-z.]*\/?\/\/$HOSTNAME.$DOMAIN\/?g" /usr/share/e2guardian/languages/french/alcasar-e2g.html
        $SED "s?\/\/[a-z.]*\/?\/\/$HOSTNAME.$DOMAIN\/?g" /usr/share/e2guardian/languages/ukenglish/alcasar-e2g.html

###### ALCASAR special filtering ####
# RAZ bannedphraselist
        cp $DIR_DG/lists/bannedphraselist $DIR_DG/lists/bannedphraselist.default
        $SED "s?^[^#]?#&?g" $DIR_DG/lists/bannedphraselist # (comment what is not)
# Disable URL control with regex
    cp $DIR_DG/lists/bannedregexpurllist $DIR_DG/lists/bannedregexpurllist.default
        $SED "s?^[^#]?#&?g" $DIR_DG/lists/bannedregexpurllist # (comment what is not)
# Replace the default deny HTML page (only fr & uk) --> !!! search why our pages make the server crash... 
#       [ -e /usr/share/e2guardian/languages/french/template.html.default ] || mv /usr/share/e2guardian/languages/french/template.html /usr/share/e2guardian/languages/french/template.html.default
#       cp -f $DIR_CONF/template-fr.html /usr/share/e2guardian/languages/french/template.html
#       [ -e /usr/share/e2guardian/languages/ukenglish/template.html.default ] || mv /usr/share/e2guardian/languages/ukenglish/template.html /usr/share/e2guardian/languages/ukenglish/template.html.default
#       cp -f $DIR_CONF/template.html /usr/share/e2guardian/languages/ukenglish/template.html
# Dont filtering files by extension or mime-type (empty list)
        [ -e $DIR_DG/lists/bannedextensionlist.default ] || mv $DIR_DG/lists/bannedextensionlist $DIR_DG/lists/bannedextensionlist.default
        touch $DIR_DG/lists/bannedextensionlist
        [ -e $DIR_DG/lists/bannedmimetypelist.default ] || mv $DIR_DG/lists/bannedmimetypelist $DIR_DG/lists/bannedmimetypelist.default
        touch $DIR_DG/lists/bannedmimetypelist
# Empty LAN IP list that won't be WEB filtered
        [ -e $DIR_DG/lists/exceptioniplist.default ] || mv $DIR_DG/lists/exceptioniplist $DIR_DG/lists/exceptioniplist.default
        touch $DIR_DG/lists/exceptioniplist
# Creation of ALCASAR banned site list
        [ -e $DIR_DG/lists/greysitelist.default ] || mv $DIR_DG/lists/greysitelist $DIR_DG/lists/greysitelist.default
        cat <<EOF > $DIR_DG/lists/greysitelist
# E2guardian filter config for ALCASAR
# In ALCASAR E2guardian filters only URLs (domains are filtered with unbound)
# block all SSL and CONNECT tunnels
**s
# block all SSL and CONNECT tunnels specified only as an IP
*ips
# block all sites specified only by an IP
*ip
EOF
# Creation of ALCASAR empty banned URLs list (filled later with Toulouse BL --> see BL function)
        [ -e $DIR_DG/lists/bannedurllist.default ] || mv $DIR_DG/lists/bannedurllist $DIR_DG/lists/bannedurllist.default
        cat <<EOF > $DIR_DG/lists/bannedurllist
# E2guardian filter config for ALCASAR
EOF
# Creation of files for rehabilited domains and urls
        [ -e $DIR_DG/lists/exceptionsitelist.default ] || mv $DIR_DG/lists/exceptionsitelist $DIR_DG/lists/exceptionsitelist.default
        [ -e $DIR_DG/lists/exceptionurllist.default ] || mv $DIR_DG/lists/exceptionurllist $DIR_DG/lists/exceptionurllist.default
        touch $DIR_DG/lists/exceptionsitelist
        touch $DIR_DG/lists/exceptionurllist
# Add Bing to the safesearch url regext list (parental control)
        [ -e $DIR_DG/lists/urlregexplist.default ] || cp $DIR_DG/lists/urlregexplist $DIR_DG/lists/urlregexplist.default
        cat <<EOF >> $DIR_DG/lists/urlregexplist

# Bing - add 'adlt=strict'
#"(^http://[0-9a-z]+\.bing\.[a-z]+[-/%.0-9a-z]*\?)(.*)"->"\1\2&adlt=strict"
EOF
# 'Safesearch' regex actualisation
        $SED "s?images?search?g" $DIR_DG/lists/urlregexplist
# change the google safesearch ("safe=strict" instead of "safe=vss")
        $SED "s?safe=vss?safe=strict?g" $DIR_DG/lists/urlregexplist

# Create & adapt the second group conf file (av + av_wl)
        cp $DIR_DG/e2guardianf1.conf.default $DIR_DG/e2guardianf2.conf
        $SED "s?^reportinglevel =.*?reportinglevel = 3?g" $DIR_DG/e2guardianf2.conf
        $SED "s?^groupname =.*?groupname = 'antimalware + whitelested users'?g" $DIR_DG/e2guardianf2.conf
        $SED "s?^urllist = 'name=banned,messageno=501,path=/etc/e2guardian/lists/bannedurllist'?urllist = 'name=banned,messageno=501,path=/etc/e2guardian/lists/bannedurllist.default'?g" $DIR_DG/e2guardianf2.conf # no banned urls

# create log folder
    mkdir -p /var/log/e2guardian
        chown -R e2guardian /etc/e2guardian /var/log/e2guardian
} # End of e2guardian()

##################################################################
##                       "antivirus"                            ##
## - Set the parameters of clamav and freshclam                 ##
##################################################################
antivirus()
{
# Clamd unit adaptation to e2guardian
        cp /lib/systemd/system/clamav-daemon.service /etc/systemd/system/clamav-daemon.service
        $SED "/^[Service]/a ExecStartPre=\/bin\/chown e2guardian:e2guardian \/run\/clamav" /etc/systemd/system/clamav-daemon.service
        $SED "/^[Service]/a ExecStartPre=\/bin\/mkdir -p \/run\/clamav" /etc/systemd/system/clamav-daemon.service
        cp /lib/systemd/system/clamav-daemon.socket /etc/systemd/system/clamav-daemon.socket
        $SED "s?^SocketUser=.*?SocketUser=e2guardian?g" /etc/systemd/system/clamav-daemon.socket
        $SED "s?^SocketGroup=.*?SocketGroup=e2guardian?g" /etc/systemd/system/clamav-daemon.socket
# Clamd conf adaptation to e2guardian
[ -e /etc/clamd.conf.default ] || cp /etc/clamd.conf /etc/clamd.conf.default
        $SED "s?^MaxThreads.*?MaxThreads 32?g" /etc/clamd.conf
        $SED "s?^#LogTime.*?LogTime yes?g" /etc/clamd.conf # enable logtime for each message
        $SED "s?^LogVerbose.*?LogVerbose no?g" /etc/clamd.conf
        $SED "s?^#LogRotate.*?LogRotate yes?g" /etc/clamd.conf
        $SED "s?^User.*?User e2guardian?g" /etc/clamd.conf
        $SED "s?^TemporaryDirectory.*?TemporaryDirectory /var/lib/e2guardian/tmp?g" /etc/clamd.conf
        chown -R e2guardian:e2guardian /var/log/clamav /var/lib/clamav
        chmod 775 /var/log/clamav /var/lib/clamav
        chmod 664 /var/log/clamav/*
# update virus database every 4 hours (24h/6)
        [ -e /etc/freshclam.conf.default ] || cp /etc/freshclam.conf /etc/freshclam.conf.default
        $SED "s?^Checks.*?Checks 6?g" /etc/freshclam.conf
        $SED "s?^NotifyClamd.*?# NotifyClamd /etc/clamd.conf?g" /etc/freshclam.conf
        $SED "s?^DatabaseOwner.*?DatabaseOwner e2guardian?g" /etc/freshclam.conf
        $SED "/^DatabaseMirror/a DatabaseMirror db.fr.clamav.net" /etc/freshclam.conf
        $SED "s?^MaxAttempts.*?MaxAttempts 3?g" /etc/freshclam.conf
        # update now
        /usr/bin/freshclam --no-warnings --quiet
} # End of antivirus()

##############################################################
##                        "ulogd"                           ##
## - Ulog config for multi-log files                        ##
##############################################################
ulogd()
{
# Three instances of ulogd (three different logfiles)
        [ -d /var/log/firewall ] || mkdir -p /var/log/firewall
        nl=1
        for log_type in traceability ssh ext-access
        do
                cp -f /lib/systemd/system/ulogd.service /etc/systemd/system/ulogd-$log_type.service
                [ -e /var/log/firewall/$log_type.log ] || echo "" > /var/log/firewall/$log_type.log
                cp -f $DIR_CONF/ulogd-sample.conf /etc/ulogd-$log_type.conf
                $SED "s?^group=.*?group=$nl?g" /etc/ulogd-$log_type.conf
                cat << EOF >> /etc/ulogd-$log_type.conf
[emu1]
file="/var/log/firewall/$log_type.log"
sync=1
EOF
                $SED "s?^ExecStart=.*?ExecStart=/usr/sbin/ulogd -c /etc/ulogd-$log_type.conf $ULOGD_OPTIONS?g" /etc/systemd/system/ulogd-$log_type.service
                nl=`expr $nl + 1`
        done
        chown -R root:apache /var/log/firewall
        chmod 750 /var/log/firewall
        chmod 640 /var/log/firewall/*
}  # End of ulogd()

##########################################################
##                     "nfsen"                          ##
## - configure NetFlow collector (nfcapd)               ##
## - configure NetFlow grapher (nfsen-ng)               ##
##########################################################
nfsen()
{
        groupadd -f nfcapd
        id -u nfcapd >/dev/null 2>&1 || useradd -r -g nfcapd -s /bin/false -c "system user for nfcapd" nfcapd
# nfcapd unit for systemd
        cat << EOF > /etc/systemd/system/nfcapd.service
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.

# This unit launches nfcapd (a Netflow collector).
[Unit]
Description=Netflow Capture Daemon
After=network-online.target iptables.service

[Service]
Type=exec
ExecStartPre=/bin/mkdir -p /run/nfcapd
ExecStartPre=/bin/chown nfcapd:nfcapd /run/nfcapd
PIDFile=/run/nfcapd/nfcapd.pid
ExecStart=/usr/bin/nfcapd -w -D -b 127.0.0.1 -p 2055 -u nfcapd -g nfcapd -B 200000 -t 300 -S 7 -z -P /run/nfcapd/nfcapd.pid -I alcasar_netflow -l /var/log/nfsen/profiles-data/live/alcasar_netflow
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target
EOF
    [ -d /var/log/nfsen/profiles-data/live/alcasar_netflow ] || mkdir -p /var/log/nfsen/profiles-data/live/alcasar_netflow
    [ -d /run/nfcapd ] || mkdir -p /run/nfcapd
    chown -R nfcapd:nfcapd /var/log/nfsen /run/nfcapd
} # End of nfsen()

###########################################################
##                       "vnstat"                        ##
## - Initialization of vnstat and vnstat-dashboard       ##
###########################################################
vnstat()
{
# vnstat
        [ -e /etc/vnstat.conf.default ] || cp /etc/vnstat.conf /etc/vnstat.conf.default
        $SED "s?^Interface.*?Interface \"$EXTIF\"?g" /etc/vnstat.conf
        $SED "s?^DatabaseDir.*?DatabaseDir /var/log/vnstat?g" /etc/vnstat.conf
        $SED "s?^MaxBandwidth.*?MaxBandwidth 10000?g" /etc/vnstat.conf
# vnstat-dashboard
        $SED "s?^\$thisInterface.*?\$thisInterface = \"$EXTIF\";?" $DIR_ACC/manager/vnstat/index.php
        cp /lib/systemd/system/vnstat.service /etc/systemd/system/vnstat.service
        $SED "s?^PIDFile=.*?PIDFile=/run/vnstat/vnstat.pid?g" /etc/systemd/system/vnstat.service
} # End of vnstat()

###################################################################
##                           "dnsmasq"                           ##
## - creation of the conf files of dnsmasq (whitelist for ipset )##
###################################################################
dnsmasq()
{
        [ -d /var/log/dnsmasq ] || mkdir /var/log/dnsmasq
        [ -e /etc/dnsmasq.conf.default ] || mv /etc/dnsmasq.conf /etc/dnsmasq.conf.default
        # dnsmasq listen on udp 55 ("dnsmasq with whitelist")
        cat << EOF > /etc/dnsmasq-whitelist.conf
# Configuration file for "dnsmasq with whitelist"
# ADD Toulouse university whitelist domains
pid-file=/run/dnsmasq-whitelist.pid
listen-address=127.0.0.1
port=55
no-dhcp-interface=lo
bind-interfaces
cache-size=1024
domain-needed
expand-hosts
bogus-priv
filterwin2k
ipset=/#/wl_ip_allowed  # dynamically add the resolv IP address in the Firewall rules
server=$DNS1
server=$DNS2
EOF

# Don't run dnsmasq service. Create dnsmasq-whitelist unit
        systemctl disable dnsmasq.service
        cp -f /lib/systemd/system/dnsmasq.service /etc/systemd/system/dnsmasq-whitelist.service
        $SED "s?^ExecStart=.*?ExecStart=/usr/sbin/dnsmasq -C /etc/dnsmasq-whitelist.conf?g" /etc/systemd/system/dnsmasq-whitelist.service
        $SED "s?^PIDFile=.*?PIDFile=/run/dnsmasq-whitelist.pid?g" /etc/systemd/system/dnsmasq-whitelist.service
} # End of dnsmasq()

#########################################################
##                     "unbound"                       ##
## - create the conf files for 4 unbound services      ##
## - create the systemd files for 4 unbound services   ##
#########################################################
unbound ()
{
        [ -d /etc/unbound/conf.d ] || mkdir -p /etc/unbound/conf.d
        [ -d /etc/unbound/conf.d/common ] || mkdir /etc/unbound/conf.d/common
        [ -d /etc/unbound/conf.d/common/local-forward ] || mkdir /etc/unbound/conf.d/common/local-forward
        [ -d /etc/unbound/conf.d/common/local-dns ] || mkdir /etc/unbound/conf.d/common/local-dns
        [ -d /etc/unbound/conf.d/forward ] || mkdir /etc/unbound/conf.d/forward
        [ -d /etc/unbound/conf.d/blacklist ] || mkdir /etc/unbound/conf.d/blacklist
        [ -d /etc/unbound/conf.d/whitelist ] || mkdir /etc/unbound/conf.d/whitelist
        [ -d /etc/unbound/conf.d/blackhole ] || mkdir /etc/unbound/conf.d/blackhole
        [ -d /var/log/unbound ] || mkdir /var/log/unbound
        chown unbound:unbound /var/log/unbound
        [ -e /etc/unbound/unbound.conf.default ] || cp /etc/unbound/unbound.conf /etc/unbound/unbound.conf.default

# Forward zone configuration file for all unbound dns servers
        cat << EOF > /etc/unbound/conf.d/common/forward-zone.conf
forward-zone:
        name: "."
        forward-addr: $DNS1
        forward-addr: $DNS2
EOF

# Custom configuration file for manual DNS configuration
        cat << EOF > /etc/unbound/conf.d/common/local-forward/custom.conf
## Ajouter un bloc pour chaque nom de domaine géré par un autre seveur DNS
## Add one block for each domain name managed by an other DNS server
##
## Example:
##
## server:
##     local-zone: "<your_domain>." transparent
## forward-zone:
##     name: "<your_domain>."
##     forward-addr: <@IP_domain_server>
##
EOF

# Configuration file of ALCASAR main domains for $INTIF
        cat << EOF > /etc/unbound/conf.d/common/local-dns/${INTIF}.conf
server:
        local-data: "$HOSTNAME.$DOMAIN A $PRIVATE_IP"
        local-data-ptr: "$PRIVATE_IP $HOSTNAME.$DOMAIN"
EOF

# Configuration file for lo of forward unbound
        cat << EOF > /etc/unbound/conf.d/forward/iface.lo.conf
server:
        interface: 127.0.0.1@53
        access-control-view: 127.0.0.1/8 lo
view:
        name: "lo"
        local-data: "$HOSTNAME A 127.0.0.1"
        local-data: "$HOSTNAME.$DOMAIN A 127.0.0.1"
        local-data-ptr: "127.0.0.1 $HOSTNAME.$DOMAIN"
        view-first: yes
EOF

# Configuration file for $INTIF of forward unbound
        cat << EOF > /etc/unbound/conf.d/forward/iface.${INTIF}.conf
server:
        interface: ${PRIVATE_IP}@53
        access-control-view: $PRIVATE_NETWORK_MASK $INTIF
view:
        name: "$INTIF"
        view-first: yes
EOF

# Configuration file for main unbound
        cat << EOF > /etc/unbound/unbound.conf
server:
        verbosity: 1
        hide-version: yes
        hide-identity: yes
        do-ip6: no
        include: /etc/unbound/conf.d/common/forward-zone.conf
        include: /etc/unbound/conf.d/common/local-forward/*
        include: /etc/unbound/conf.d/common/local-dns/*
        include: /etc/unbound/conf.d/forward/*
EOF

# Configuration file for $INTIF of blacklist unbound
        cat << EOF > /etc/unbound/conf.d/blacklist/iface.${INTIF}.conf
server:
        interface: ${PRIVATE_IP}@54
        access-control: $PRIVATE_IP_MASK allow
        access-control-tag: $PRIVATE_IP_MASK "blacklist"
        access-control-tag-action: $PRIVATE_IP_MASK "blacklist" redirect
        access-control-tag-data: $PRIVATE_IP_MASK "blacklist" "A $PRIVATE_IP"
EOF

# Configuration file for blacklist unbound
        cat << EOF > /etc/unbound/unbound-blacklist.conf
server:
        verbosity: 1
        hide-version: yes
        hide-identity: yes
        do-ip6: no
        logfile: "/var/log/unbound/unbound-blacklist.log"
        chroot: ""
        define-tag: "blacklist"
        log-local-actions: yes
        include: /etc/unbound/conf.d/common/forward-zone.conf
        include: /etc/unbound/conf.d/common/local-forward/*
        include: /etc/unbound/conf.d/common/local-dns/*
        include: /etc/unbound/conf.d/blacklist/*
        include: /usr/local/share/unbound-bl-enabled/*
EOF

# Configuration file for $INTIF of whitelist unbound
        cat << EOF > /etc/unbound/conf.d/whitelist/iface.${INTIF}.conf
server:
        interface: ${PRIVATE_IP}@55
        access-control: $PRIVATE_IP_MASK allow
        access-control-tag: $PRIVATE_IP_MASK "whitelist"
        access-control-tag-action: $PRIVATE_IP_MASK "whitelist" redirect
        access-control-tag-data: $PRIVATE_IP_MASK "whitelist" "A $PRIVATE_IP"
EOF

# Configuration file for whitelist unbound
        cat << EOF > /etc/unbound/unbound-whitelist.conf
server:
        verbosity: 1
        hide-version: yes
        hide-identity: yes
        do-ip6: no
        do-not-query-localhost: no
        define-tag: "whitelist"
        local-zone: "." transparent
        local-zone-tag: "." "whitelist"
        include: /etc/unbound/conf.d/common/local-forward/*
        include: /etc/unbound/conf.d/common/local-dns/*
        include: /etc/unbound/conf.d/whitelist/*
        include: /usr/local/share/unbound-wl-enabled/*
forward-zone:
        name: "."
        forward-addr: 127.0.0.1@55
EOF

# Configuration file for $INTIF of blackhole unbound
        cat << EOF > /etc/unbound/conf.d/blackhole/iface.${INTIF}.conf
server:
        interface: ${PRIVATE_IP}@56
        access-control-view: $PRIVATE_NETWORK_MASK $INTIF
view:
        name: "$INTIF"
        local-zone: "." redirect
        local-data: ". A $PRIVATE_IP"
EOF

# Configuration file for blackhole unbound
        cat << EOF > /etc/unbound/unbound-blackhole.conf
server:
        verbosity: 1
        hide-version: yes
        hide-identity: yes
        do-ip6: no
        include: /etc/unbound/conf.d/common/local-forward/*
        include: /etc/unbound/conf.d/common/local-dns/*
        include: /etc/unbound/conf.d/blackhole/*
EOF
        cp /lib/systemd/system/unbound.service /etc/systemd/system/unbound.service
        $SED "s?^ExecStart=.*?ExecStart=/usr/sbin/unbound -d -c /etc/unbound/unbound.conf?g" /etc/systemd/system/unbound.service
        $SED "s?^After=.*?After=syslog.target network-online.target chilli.service?g" /etc/systemd/system/unbound.service
        for list in blacklist blackhole whitelist
        do
                cp -f /lib/systemd/system/unbound.service /etc/systemd/system/unbound-$list.service
                $SED "s?^ExecStart=.*?ExecStart=/usr/sbin/unbound -d -c /etc/unbound/unbound-$list.conf?g" /etc/systemd/system/unbound-$list.service
                $SED "s?^PIDFile=.*?PIDFile=/run/unbound-$list.pid?g" /etc/systemd/system/unbound-$list.service
        done
        $SED "s?^After=.*?After=syslog.target network-online.target chilli.service dnsmasq-whitelist.service?g" /etc/systemd/system/unbound-whitelist.service
} # End of unbound()

##################################################
##                   "dhcpd"                    ##
##################################################
dhcpd()
{
        [ -e /etc/dhcpd.conf.default ] || cp /etc/dhcpd.conf /etc/dhcpd.conf.default
        cat <<EOF > /etc/dhcpd.conf
ddns-update-style none;
subnet $PRIVATE_NETWORK netmask $PRIVATE_NETMASK {
        option routers $PRIVATE_IP;
        option subnet-mask $PRIVATE_NETMASK;
        option domain-name-servers $PRIVATE_IP;
        range dynamic-bootp $PRIVATE_SECOND_IP $PRIVATE_LAST_IP;
        default-lease-time 21600;
        max-lease-time 43200;
}
EOF
} # End of dhcpd()

##########################################################
##                         "BL"                         ##
## - copy & adapt Toulouse BL to ALCASAR architecture   ##
##     - domain names for unbound-bl & unbound-wl       ##
##     - URLs for E²guardian                            ##
##     - IPs for NetFilter                              ##
## - copy additional BLs (TOR + Ultrasurf + C&C)        ##
##########################################################
BL()
{
# copy the Toulouse university BL in order to be adapted to ALCASAR architecture (alcasar-bl.sh -adapt)
        rm -rf $DIR_DG/lists/blacklists
        mkdir -p /tmp/blacklists
        cp $DIR_BLACKLIST/blacklists.tar.gz /tmp/blacklists/
# creation of the additional BL and WL categorie named "ossi" (for domain names & ip only)
        mkdir -p $DIR_DG/lists/blacklists/ossi-bl
        touch $DIR_DG/lists/blacklists/ossi-bl/domains
        echo "ossi-bl" >> $DIR_DEST_ETC/alcasar-bl-categories-enabled
        mkdir -p $DIR_DG/lists/blacklists/ossi-wl
        touch $DIR_DG/lists/blacklists/ossi-wl/domains
        echo "ossi-wl" >> $DIR_DEST_ETC/alcasar-wl-categories-enabled
# add additional BL files
        for x in $(ls $DIR_BLACKLIST | grep -v "^blacklists")
        do
                mkdir $DIR_DG/lists/blacklists/ossi-bl-$x
                cp $DIR_BLACKLIST/$x  $DIR_DG/lists/blacklists/ossi-bl-$x/domains
                echo "ossi-bl-$x" >> $DIR_DEST_ETC/alcasar-bl-categories-enabled
        done
        chown -R e2guardian:apache $DIR_DG
        chown -R root:apache $DIR_DEST_SHARE
        chmod -R g+rw $DIR_DG $DIR_DEST_SHARE
# adapt the Toulouse BL to ALCASAR architecture
        $DIR_DEST_BIN/alcasar-bl.sh --adapt
# enable the default categories
        $DIR_DEST_BIN/alcasar-bl.sh --cat_choice
        rm -rf /tmp/blacklists
} # End of BL()

#######################################################
##                    "cron"                         ##
## - write all cron & anacron files                  ##
#######################################################
cron()
{
# 'crontab' with standard cron at midnight instead of 4:0 am (default)
        [ -e /etc/crontab.default ] || cp /etc/crontab /etc/crontab.default
        cat <<EOF > /etc/crontab
SHELL=/usr/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root nice -n 19 run-parts --report /etc/cron.hourly
02 0 * * * root nice -n 19 run-parts --report /etc/cron.daily
22 0 * * 0 root nice -n 19 run-parts --report /etc/cron.weekly
42 0 1 * * root nice -n 19 run-parts --report /etc/cron.monthly
EOF
        [ -e /etc/anacrontab.default ] || cp /etc/anacrontab /etc/anacrontab.default
        cat <<EOF >> /etc/anacrontab
7       8       cron.MysqlDump          nice /etc/cron.d/alcasar-mysql
7       10      cron.logExport          nice /etc/cron.d/alcasar-archive
EOF
        cat <<EOF > /etc/cron.d/alcasar-mysql
# Verify, repair and export users database (every monday at 4:45 am)
45 4 * * 1 root $DIR_DEST_BIN/alcasar-mysql.sh --dump
# Remove users whose expiration date is exceeded for more more than 7 days (every Monday at 4:40 am)
40 4 * * * root $DIR_DEST_BIN/alcasar-mysql.sh --expire_user 2>&1 >/dev/null
EOF
        cat <<EOF > /etc/cron.d/alcasar-archive
# Archiving logs (traceability & users database) (every Monday at 5:35 am)
35 5 * * 1 root $DIR_DEST_BIN/alcasar-archive.sh --now
EOF
        cat <<EOF > /etc/cron.d/alcasar-ticket-clean
# Remove password files (created when importing users by CSV files) and user's PDF voucher (every hours at 30')
30 * * * *  root $DIR_DEST_BIN/alcasar-ticket-clean.sh
EOF
        cat <<EOF > /etc/cron.d/alcasar-distrib-updates
# Update the system and reboot if needed (everyday at 3:30 am)
30 3 * * *  root /usr/sbin/urpmi --auto-update --auto 2>&1 ; /usr/local/bin/alcasar-daemon.sh -after-update
EOF
        cat <<EOF > /etc/cron.d/alcasar-connections-stats
# Connection stats update (accounting). These Perl scripts are from "dialup_admin" (cf. wiki.freeradius.org/Dialup_admin).
# 'alcasar-tot_stats' : aggregate the daily connections of users and write it in the table 'totacct' (everyday at 1:01 pm)
# 'alcasar-monthly_tot_stat' : aggregate the monthly connections of users and write it in table 'mtotacct' (everyday at 1h05 pm)
# 'alcasar-truncate_raddact' : remove the user' session log older than 365 days (applying French law : "LCEN") (every month, the first at 01:10 pm)
# 'alcasar-clean_radacct' : close the sessions openned for more than 30 days (every month, the first at 01:15 pm)
# 'alcasar-activity_report.sh' : generate an activity report in PDF (every sunday at 5:35 pm)
1 1 * * * root $DIR_DEST_BIN/alcasar-tot_stats > /dev/null 2>&1
5 1 * * * root $DIR_DEST_BIN/alcasar-monthly_tot_stats > /dev/null 2>&1
10 1 1 * * root $DIR_DEST_BIN/alcasar-truncate_radacct > /dev/null 2>&1
15 1 1 * * root $DIR_DEST_BIN/alcasar-clean_radacct > /dev/null 2>&1
35 5 * * 0 root $DIR_DEST_BIN/alcasar-activity_report.sh > /dev/null 2>&1
EOF
        cat <<EOF > /etc/cron.d/alcasar-watchdog
# 'alcasar-watchdog.sh' : run the "watchdog" (every 10')
# 'alcasar-flush_ipset_wl.sh' : empty the IPSET of the whitelisted IP loaded dynamically with dnsmasq-whitelist hook (every sunday at 0:05 am)
# 'alcasar-watchdog.sh --disconnect-permanent-users' : disconnect users with attribute "Alcasar-Status-Page-Must-Stay-Open" (daily --> see "cron.daily")
# 'alcasar-watchdog-hl.sh' : (optionnaly) remove the IP 0.0.0.0 from chilli cache memory
*/10 * * * * root $DIR_DEST_BIN/alcasar-watchdog.sh > /dev/null 2>&1
0 5 * * 0 root $DIR_DEST_BIN/alcasar-flush_ipset_wl.sh > /dev/null 2>&1
@daily root $DIR_DEST_BIN/alcasar-watchdog.sh --disconnect-permanent-users > /dev/null 2>&1
#* * * * * root $DIR_DEST_BIN/alcasar-watchdog-hl.sh > /dev/null 2>&1
EOF
        cat <<EOF > /etc/cron.d/alcasar-daemon-watchdog
# start dead daemons (after boot process and every 20')
@reboot root $DIR_DEST_BIN/alcasar-daemon.sh > /dev/null 2>&1
*/20 * * * * root $DIR_DEST_BIN/alcasar-daemon.sh > /dev/null 2>&1
EOF
        cat <<EOF > /etc/cron.d/alcasar-rsync-bl
# Automatic update the BL (every 12 hours). The enabled categories are listed in '/usr/local/etc/update_cat.conf' (no sync if empty).
0 */12 * * * root $DIR_DEST_BIN/alcasar-bl-autoupdate.sh --update_cat > /dev/null 2>&1
EOF
        cat <<EOF > /etc/cron.d/alcasar-rsync-ossi_bl
# Automatic update the OSSI BLs (every 12 hours) by running the custom update scripts specified in '/usr/local/etc/update_ossi_cat.conf'.
0 */12 * * * root /bin/bash /usr/local/etc/update_ossi_cat.conf > /dev/null 2>&1
EOF
        cat <<EOF > /etc/cron.d/alcasar-letsencrypt
# Automatic renew the Let's Encrypt certificate (daily --> see "cron.daily")
@daily root $DIR_DEST_BIN/alcasar-letsencrypt.sh --cron > /dev/null 2>&1
EOF
        cat <<EOF > /etc/cron.d/alcasar-nfcapd-expire
# Remove netflow files older than one year (daily --> see "cron.daily")
@daily root /usr/bin/nfexpire -e /var/log/nfsen/profiles-data/live/alcasar_netflow -t 365d
EOF
# removing the users crons
        rm -f /var/spool/cron/*
} # End of cron()

########################################################################
##                              "Fail2Ban"                            ##
##- Adapt conf file to ALCASAR                                        ##
##- Secure items : DDOS, SSH-Brute-Force, Intercept & ACC brute-Force ##
########################################################################
fail2ban()
{
# adapt fail2ban to Mageia (fedora like) & ALCASAR behaviour
        [ -e /etc/fail2ban/jail.conf.default ] || cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.conf.default
        $SED "s?^before =.*?before = paths-fedora.conf?g" /etc/fail2ban/jail.conf

# add 5 jails and their filters
## sshd : Ban after 3 failed attempts (ie. brute-force). This "jail" uses the default "sshd" f2b filter.
        cat << EOF > /etc/fail2ban/jail.d/01-alcasar_sshd.conf
[sshd]
enabled = true
#enabled  = false
maxretry = 3
bantime = 3m
findtime = 5m
EOF

## lighttpd-auth : Ban after 3 failed attempts on ACC. This "jail" uses the default "lighttpd-auth" f2b filter.
        cat << EOF > /etc/fail2ban/jail.d/02-alcasar_lighttpd-auth.conf
[lighttpd-auth]
enabled = true
#enabled  = false
maxretry = 3
bantime = 3m
findtime = 3m
EOF

## mod-evasive : Ban after 3 failed retrieve page attempts (ie : unknown page)
        cat << EOF > /etc/fail2ban/jail.d/03-alcasar_mod-evasive.conf
[alcasar_mod-evasive]
#enabled = true
enabled = false
backend = auto
filter = alcasar_mod-evasive
action = iptables-allports[name=alcasar_mod-evasive]
logpath = /var/log/lighttpd/access.log
maxretry = 3
bantime = 3m
findtime = 3m
EOF
        cat << EOF > /etc/fail2ban/filter.d/alcasar_mod-evasive.conf
[Definition]
failregex =  <HOST> .+\] "[^"]+" 403
ignoreregex =
EOF

### alcasar_intercept : ban after 5 failed user login attemps on intercept.php
        cat << EOF > /etc/fail2ban/jail.d/04-alcasar_intercept.conf
[alcasar_intercept]
enabled = true
#enabled = false
backend = auto
filter = alcasar_intercept
action = iptables-allports[name=alcasar_intercept]
logpath = /var/log/lighttpd/access.log
maxretry = 5
bantime = 3m
findtime = 3m
EOF
        cat << EOF > /etc/fail2ban/filter.d/alcasar_intercept.conf
[Definition]
failregex = <HOST> .* \"GET \/intercept\.php\?res=failed\&reason=reject
ignoreregex =
EOF

## alcasar_change-pwd : ban after 5 failed user change password attempts
        cat << EOF > /etc/fail2ban/jail.d/05-alcasar_change-pwd.conf
[alcasar_change-pwd]
enabled = true
#enabled = false
backend = auto
filter = alcasar_change-pwd
action = iptables-allports[name=alcasar_change-pwd]
logpath = /var/log/lighttpd/access.log
maxretry = 5
bantime = 3m
findtime = 3m
EOF
        cat << EOF > /etc/fail2ban/filter.d/alcasar_change-pwd.conf
[Definition]
failregex = <HOST> .* \"POST \/password\.php
ignoreregex =
EOF

# allow reading of 2 log files (fail2ban & watchdog).
        [ -e /var/log/fail2ban.log ] || /usr/bin/touch /var/log/fail2ban.log
        [ -e $DIR_SAVE/security/watchdog.log ] || /usr/bin/touch $DIR_SAVE/security/watchdog.log
        chmod 644 /var/log/fail2ban.log
        chmod 644 $DIR_SAVE/security/watchdog.log
        /usr/bin/touch /var/log/auth.log
# fail2ban unit
        cp /lib/systemd/system/fail2ban.service /etc/systemd/system/fail2ban.service
        $SED '/ExecStart=/a\ExecStop=/usr/bin/fail2ban-client stop' /etc/systemd/system/fail2ban.service
        $SED '/Type=/a\PIDFile=/run/fail2ban/fail2ban.pid' /etc/systemd/system/fail2ban.service
        $SED '/After=*/c After=syslog.target network.target lighttpd.service' /etc/systemd/system/fail2ban.service
} # End of fail2ban()

########################################################
##                  "gammu_smsd"                      ##
## - Creating of SMS management database              ##
## - Write the gammu a gammu_smsd conf files          ##
########################################################
gammu_smsd()
{
# Create 'gammu' system user
        groupadd -f gammu_smsd
        useradd -r -g gammu_smsd -s /bin/false -c "system user for gammu_smsd" gammu_smsd
        usermod -a -G dialout gammu_smsd

# Create 'gammu' database
        MYSQL="/usr/bin/mysql -uroot -p$mysqlpwd --execute"
        $MYSQL "CREATE DATABASE IF NOT EXISTS $DB_GAMMU; GRANT ALL ON $DB_GAMMU.* TO $DB_USER@localhost IDENTIFIED BY '$radiuspwd'; FLUSH PRIVILEGES;"
# Add a gammu database structure
        /usr/bin/mysql -u$DB_USER -p$radiuspwd $DB_GAMMU < $DIR_CONF/empty-gammu-smsd-db.sql

# Config file for the gammu_smsd daemon & gammu (ttyUSB0 as default com port)
        cat << EOF > /etc/gammurc
[gammu]
device = /dev/ttyUSB0
connection = at115200
EOF

        cat << EOF > /etc/gammu_smsd_conf
[gammu]
port = /dev/ttyUSB0
connection = at115200

[smsd]
PIN = 1234
logfile = /var/log/gammu-smsd/gammu-smsd.log
logformat = textall
debuglevel = 0

service = sql
driver = native_mysql
user = $DB_USER
password = $radiuspwd
pc = localhost
database = $DB_GAMMU

RunOnReceive = sudo $DIR_DEST_BIN/alcasar-sms.sh --new_sms

StatusFrequency = 30
;LoopSleep = 2

;ResetFrequency = 300
;HardResetFrequency = 120

CheckSecurity = 1
CheckSignal = 1
CheckBattery = 0
EOF
        chmod 755 /etc/gammu_smsd_conf /etc/gammurc

# Create the systemd unit
        cat << EOF > /etc/systemd/system/gammu-smsd.service
[Unit]
Description=SMS daemon for Gammu
Documentation=man:gammu-smsd(1)
After=network.target mysql.service

[Service]
Type=forking
ExecStart=/usr/bin/gammu-smsd --config /etc/gammu_smsd_conf --user=gammu_smsd --group=gammu_smsd --pid=/run/gammu-smsd.pid --daemon
ExecReload=/bin/kill -HUP $MAINPID
ExecStopPost=/bin/rm -f /run/gammu-smsd.pid
PIDFile=/run/gammu-smsd.pid

[Install]
WantedBy=multi-user.target
EOF

# Log folder for gammu-smsd
        [ -d /var/log/gammu-smsd ] || mkdir /var/log/gammu-smsd
        chmod 755 /var/log/gammu-smsd

# Udev rule for Modeswitch (switch from "mass_storage" mode to "ttyUSB" modem) needed with some Huawei MODEM (idVendor: 12d1)
# normally not needed now since modeswitch is managed by udev (see Mageia RPM)
#cat << EOF > /lib/udev/rules.d/66-huawei.rules
#KERNEL=="ttyUSB0",ATTRS{idVendor}=="12d1",RUN+="$DIR_DEST_BIN/alcasar-sms.sh --mode"
#EOF
# Udev rule for fixing the enumeration of ttyUSB port on some MODEM (when they switch randomly the order of their ports at boot time)
# example : http://hintshop.ludvig.co.nz/show/persistent-names-usb-serial-devices/

} # End of gammu_smsd()

########################################################
##                      "msec"                        ##
## - Apply the "fileserver" security level            ##
## - remove the "system request" for rebooting        ##
## - Fix several file permissions                     ##
########################################################
msec()
{

# Apply fileserver security level
        [ -e /etc/security/msec/security.conf.default ] || cp /etc/security/msec/security.conf /etc/security/msec/security.conf.default
        echo "BASE_LEVEL=fileserver" > /etc/security/msec/security.conf

# Set permissions monitoring and enforcement
cat <<EOF > /etc/security/msec/perm.local
/var/log/firewall/                      root.apache     750
/var/log/firewall/*                     root.apache     640
/etc/security/msec/perm.local           root.root       640
/etc/security/msec/level.local          root.root       640
/etc/freeradius-web                     root.apache     750
/etc/freeradius-web/admin.conf          root.apache     640
/etc/raddb/client.conf                  radius.radius   640
/etc/raddb/radius.conf                  radius.radius   640
/etc/raddb/mods-available/ldap          radius.apache   660
/etc/raddb/sites-available/alcasar      radius.apache   660
/etc/pki/CA/                            root.apache     750 force
/etc/pki/CA/*                           root.apache     640 force 
/etc/pki/CA/private/                    root.root       700 force
/etc/pki/CA/private/*                   root.root       600 force
/etc/pki/tls/private/                   root.apache     750 force
/etc/pki/tls/private/*                  root.apache     640 force
/var/log/clamav/                        e2guardian.e2guardian   755 force
/var/log/clamav/*                       e2guardian.e2guardian   764 force
/var/lib/clamav/                        e2guardian.e2guardian   755 force
EOF
# apply now hourly & daily checks
        /usr/sbin/msec
        /etc/cron.weekly/msec

} # End of msec()

##################################################################
##                   Fonction "letsencrypt"                     ##
## - Install Let's Encrypt client                               ##
## - Prepare Let's Encrypt ALCASAR configuration file           ##
##################################################################
letsencrypt()
{
        echo "Installing Let's Encrypt client..."
# Remove potential old installers
        rm -rf /tmp/acme.sh-*
# Extract acme.sh
        tar xzf ./conf/letsencrypt-client/acme.sh-*.tar.gz -C /tmp/
        pwdInstall=$(pwd)
        cd /tmp/acme.sh-* || { echo "Unable to find ACME directory"; exit 1; }
        acmesh_installDir="/opt/acme.sh"
        acmesh_confDir="/usr/local/etc/letsencrypt"
        acmesh_userAgent="ALCASAR"
# Install acme.sh
        ./acme.sh --install \
                --home $acmesh_installDir \
                --config-home $acmesh_confDir/data \
                --certhome $acmesh_confDir/certs \
                --accountkey $acmesh_confDir/ca/account.key \
                --accountconf $acmesh_confDir/data/account.conf \
                --useragent $acmesh_userAgent \
                --nocron \
                > /dev/null
        if [ $? -ne 0 ]; then
                echo "Error during installation of Let's Encrypt client (acme.sh)."
        fi
# Create configuration file
        cat <<EOF > /usr/local/etc/alcasar-letsencrypt
email=
dateIssueRequest=
domainRequest=
challenge=
dateIssued=
dnsapi=
dateNextRenewal=
EOF
        cd $pwdInstall || { echo "Unable to find $pwdInstall directory"; exit 1; }
        rm -rf /tmp/acme.sh-*
} # End of letsencrypt()

##################################################################
##                       "mail_service"                         ##
## - Install Postfix conf for email registration method         ##
##################################################################
mail_service()
{
        [ -e /etc/postfix/main.cf.orig ] || cp /etc/postfix/main.cf /etc/postfix/main.cf.orig
        cat << EOT >> /etc/postfix/main.cf
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd
smtpd_banner = \$myhostname ESMTP
relayhost =
myhostname = $HOSTNAME.$DOMAIN
EOT
        chown -R postfix:postfix /var/lib/postfix
} # end of mail_service

##################################################################
##                    Fonction "post_install"                   ##
## - Modifying banners (locals et ssh) & prompts                ##
## - SSH config                                                 ##
## - sudoers config & files security                            ##
## - log rotate & ANSSI security parameters                     ##
## - Apply former conf in case of an update                     ##
##################################################################
post_install()
{
# change the SSHD options
        cp -f $DIR_CONF/banner /etc/ssh/alcasar-banner-ssh
        echo " V$VERSION" >> /etc/ssh/alcasar-banner-ssh
        chmod 644 /etc/ssh/alcasar-banner-ssh ; chown root:root /etc/ssh/alcasar-banner-ssh
        [ -e /etc/ssh/sshd_config.default ] || cp /etc/ssh/sshd_config /etc/ssh/sshd_config.default
        $SED "s?^Banner.*?Banner /etc/ssh/alcasar-banner-ssh?g" /etc/ssh/sshd_config
        $SED "s?^#Banner.*?Banner /etc/ssh/alcasar-banner-ssh?g" /etc/ssh/sshd_config
# sshd listens on EXTIF & INTIF
        $SED "s?^#ListenAddress 0\.0\.0\.0.*?ListenAddress 0\.0\.0\.0?g" /etc/ssh/sshd_config
# sshd authorized certificate for root login
        $SED "s?^PermitRootLogin.*?PermitRootLogin without-password?g" /etc/ssh/sshd_config
        $SED "s?^X11Forwarding.*?#X11Forwarding yes?g" /etc/ssh/sshd_config
# ALCASAR conf file
        echo "HTTPS_LOGIN=off" >> $CONF_FILE
        echo "HTTPS_CHILLI=off" >> $CONF_FILE
        echo "SSH=on" >> $CONF_FILE
        echo "SSH_ADMIN_FROM=0.0.0.0/0.0.0.0" >> $CONF_FILE
        echo "LDAP=off" >> $CONF_FILE
        echo "LDAP_SERVER=127.0.0.1" >> $CONF_FILE
        echo "LDAP_BASE=cn=Users;dc=serverad;dc=localdomain" >> $CONF_FILE
        echo "LDAP_UID=sAMAccountName" >> $CONF_FILE
        echo "LDAP_FILTER=" >> $CONF_FILE
        echo "LDAP_USER=alcasar" >> $CONF_FILE
        echo "LDAP_PASSWORD=" >> $CONF_FILE
        echo "LDAP_SSL=on" >> $CONF_FILE
        echo "LDAP_CERT_REQUIRED=" >> $CONF_FILE
        echo "SMS=off" >> $CONF_FILE
        echo "SMS_NUM=" >> $CONF_FILE
        echo "MAIL=off" >> $CONF_FILE
        echo "MAIL_TYPE=" >> $CONF_FILE
        echo "MAIL_SMTP_IP=" >> $CONF_FILE
        echo "MAIL_SMTP_PORT=" >> $CONF_FILE
        echo "MAIL_ADDR=" >> $CONF_FILE
        echo "MAIL_PASSWORD=" >> $CONF_FILE
        echo "MAIL_WHITEDOMAIN=" >> $CONF_FILE
        echo "MAIL_ADMIN=" >> $CONF_FILE
        echo "BL_PUREIP=on" >> $CONF_FILE
        echo "BL_SAFESEARCH=off" >> $CONF_FILE
        echo "WL_SAFESEARCH=off" >> $CONF_FILE
        echo "IOT_CAPTURE=off" >> $CONF_FILE
        echo "WIFI4EU=off" >> $CONF_FILE
        echo "WIFI4EU_CODE=123e4567-e89b-12d3-a456-426655440000" >> $CONF_FILE
        echo "MULTIWAN=off" >> $CONF_FILE
# Prompt customisation (colors)
        [ -e /etc/bashrc.default ]  || cp /etc/bashrc /etc/bashrc.default
        cp -f $DIR_CONF/bashrc /etc/. ; chmod 644 /etc/bashrc ; chown root:root /etc/bashrc
        $SED "s?^ORGANISME.*?ORGANISME=$ORGANISME?g" /etc/bashrc
        $SED "s?^alias ll=.*?alias ll=\"ls -al --color\"?g" /etc/profile.d/60alias.sh
# sudoers configuration for "apache" & "sysadmin"
        [ -e /etc/sudoers.default ]  || cp /etc/sudoers /etc/sudoers.default
        cp -f $DIR_CONF/sudoers /etc/ ; chmod 440 /etc/sudoers ; chown root:root /etc/sudoers
        $SED "s?^Host_Alias.*?Host_Alias        LAN_ORG=$PRIVATE_NETWORK/$PRIVATE_NETMASK,localhost             #réseau de l'organisme?g" /etc/sudoers
# Modify some logrotate files (gammu, ulogd)
        cp -f $DIR_CONF/logrotate.d/* /etc/logrotate.d/
        chmod 644 /etc/logrotate.d/*
# Log compression
        $SED "s?^delaycompress.*?#&?g" /etc/logrotate.conf
# actualisation des fichiers logs compressés
        for dir in firewall e2guardian lighttpd
        do
                find /var/log/$dir -type f -name "*.log-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]" -exec gzip {} \;
        done
        /usr/bin/systemctl daemon-reload
# processes started at boot time (Systemctl)
        for i in alcasar-network mysqld lighttpd php-fpm ntpd iptables unbound unbound-blacklist unbound-whitelist dnsmasq-whitelist unbound-blackhole radiusd nfcapd e2guardian clamav-daemon clamav-freshclam ulogd-ssh ulogd-traceability ulogd-ext-access chilli fail2ban vnstat sshd
        do
                /usr/bin/systemctl -q enable $i.service
        done

# disable processes at boot time (Systemctl)
        for i in ulogd gpm dhcpd
        do
                /usr/bin/systemctl -q disable $i.service
        done

# Apply some security rules (some are from French cybersecurity Agency - ANSSI)
# ignore ICMP broadcast (smurf attack)
        echo "net.ipv4.icmp_echo_ignore_broadcasts = 1" > /etc/sysctl.d/alcasar.conf
# ignore ICMP errors bogus
        echo "net.ipv4.icmp_ignore_bogus_error_responses = 1" >> /etc/sysctl.d/alcasar.conf
# remove ICMP redirects responces
        echo "net.ipv4.conf.all.accept_redirects = 0" >> /etc/sysctl.d/alcasar.conf
        echo "net.ipv4.conf.all.send_redirects = 0" >> /etc/sysctl.d/alcasar.conf
# enable SYN Cookies (Syn flood attacks)
        echo "net.ipv4.tcp_syncookies = 1" >> /etc/sysctl.d/alcasar.conf
# enable kernel antispoofing
        echo "net.ipv4.conf.all.rp_filter = 1" >> /etc/sysctl.d/alcasar.conf
# ignore source routing
        echo "net.ipv4.conf.all.accept_source_route = 0" >> /etc/sysctl.d/alcasar.conf
# set conntrack timer to 1h (3600s) instead of 5 weeks
        echo "net.netfilter.nf_conntrack_tcp_timeout_established = 3600" >> /etc/sysctl.d/alcasar.conf
# disable log_martians (ALCASAR is often installed between two private network addresses)
        echo "net.ipv4.conf.all.log_martians = 0" >> /etc/sysctl.d/alcasar.conf
# disable iptables_helpers
        echo "net.netfilter.nf_conntrack_helper = 0" >> /etc/sysctl.d/alcasar.conf
# Switch to the router mode
        echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.d/alcasar.conf
# Remove unused service ipv6
        echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.d/alcasar.conf
        echo "net.ipv6.conf.all.autoconf = 0" >> /etc/sysctl.d/alcasar.conf
        echo "net.ipv6.conf.default.disable_ipv6 = 1" >> /etc/sysctl.d/alcasar.conf
        echo "net.ipv6.conf.default.autoconf = 0" >> /etc/sysctl.d/alcasar.conf
# switch to multi-users runlevel (instead of x11)
        ln -sf /lib/systemd/system/multi-user.target /etc/systemd/system/default.target
# disable Core dump file
        [ -e /etc/security/limits.conf.default ]  || cp /etc/security/limits.conf /etc/security/limits.conf.default
        $SED "/^# End of file.*/i*\tsoft\tcore\t0\n*\thard\tcore\t0" /etc/security/limits.conf

# GRUB2 modifications (Wait time : 3s - ALCASAR entry - VGA=791 - Change the default banner
        [ -e /etc/default/grub.default ]  || cp /etc/default/grub /etc/default/grub.default
        $SED "s?^GRUB_TIMEOUT=.*?GRUB_TIMEOUT=3?g" /etc/default/grub
        $SED "s?^GRUB_DISTRIBUTOR=.*?GRUB_DISTRIBUTOR=ALCASAR?g" /etc/default/grub
        [ -e /etc/mageia-release.default ]  || cp /etc/mageia-release /etc/mageia-release.default
        vm_vga=`lsmod | egrep -c "virtio|vmwgfx"` # test if in VM
        if [ $vm_vga == 0 ] # is not a VM
        then
                cp -f $DIR_CONF/banner /etc/mageia-release # ALCASAR ASCII-Art
                echo >> /etc/mageia-release
                $SED "s?^GRUB_CMDLINE_LINUX_DEFAULT=\"?&vga=791 ?" /etc/default/grub
        fi
        if [ $Lang == "fr" ]
        then
                echo "Bienvenue sur ALCASAR V$VERSION" >> /etc/mageia-release
                echo "Connectez-vous à l'URL 'https://$HOSTNAME.$DOMAIN/acc'" >> /etc/mageia-release
        else
                echo "Welcome on ALCASAR V$VERSION" >> /etc/mageia-release
                echo "Connect to 'https://$HOSTNAME.$DOMAIN/acc'" >> /etc/mageia-release
        fi
        /usr/bin/update-grub2
# Load and apply the previous conf file
        if [ "$mode" = "update" ]
        then
                $DIR_DEST_BIN/alcasar-archive.sh --now # exports current logs in $DIR_SAVE/archive
                $DIR_DEST_BIN/alcasar-conf.sh --load
                PARENT_SCRIPT=`basename $0`
                export PARENT_SCRIPT # to avoid stop&start process during the installation process
                $DIR_DEST_BIN/alcasar-conf.sh --apply
                $DIR_DEST_BIN/alcasar-file-clean.sh # Clean & sort conf files. Add uamallowed domains to the dns-blackhole conf
                $SED "s?^INSTALL_DATE=.*?INSTALL_DATE=$DATE?g" $CONF_FILE
                $SED "s?^VERSION=.*?VERSION=$VERSION?g" $CONF_FILE
        fi
        rm -f /var/tmp/alcasar-conf*
        chown -R root:apache $DIR_DEST_ETC/*
        chmod -R 660 $DIR_DEST_ETC/*
        chmod ug+x $DIR_DEST_ETC/digest
        cd $DIR_INSTALL || { echo "Unable to find $DIR_INSTALL directory"; exit 1; }
        echo ""
        echo "#############################################################################"
        if [ $Lang == "fr" ]
                then
                echo "#                        Fin d'installation d'ALCASAR                       #"
                echo "#                                                                           #"
                echo "#         Application Libre pour le Contrôle Authentifié et Sécurisé        #"
                echo "#                     des Accès au Réseau ( ALCASAR )                       #"
                echo "#                                                                           #"
                echo "#############################################################################"
                echo
                echo "- ALCASAR sera fonctionnel après redémarrage du système"
                echo
                echo "- Lisez attentivement la documentation d'exploitation"
                echo
                echo "- Le centre de controle d'ALCASAR (ACC) est à l'adresse http://$HOSTNAME.$DOMAIN"
                echo
                echo "                   Appuyez sur 'Entrée' pour continuer"
        else
                echo "#                        End of ALCASAR install process                     #"
                echo "#                                                                           #"
                echo "#         Application Libre pour le Contrôle Authentifié et Sécurisé        #"
                echo "#                     des Accès au Réseau ( ALCASAR )                       #"
                echo "#                                                                           #"
                echo "#############################################################################"
                echo
                echo "- The system will be rebooted in order to operate ALCASAR"
                echo
                echo "- Read the exploitation documentation"
                echo
                echo "- The ALCASAR Control Center (ACC) is at http://$HOSTNAME.$DOMAIN"
                echo
                echo "                   Hit 'Enter' to continue"
        fi
        sleep 2
        if [ "$mode" == "install" ] || [ "$DEBUG_ALCASAR" == "on" ]
        then
                read
        fi
        clear
        reboot
} # End of post_install()

#####################################################################################
#                                   Main Install loop                               #
#####################################################################################
dir_exec=`dirname "$0"`
if [ $dir_exec != "." ]
then
        echo "Lancez ce programme depuis le répertoire de l'archive d'ALCASAR"
        echo "Launch this program from the ALCASAR archive directory"
        exit 0
fi
if [ $EUID -gt 0 ]
then
        echo "Vous devez être \"root\" pour installer ALCASAR (commande 'su')"
        echo "You must be \"root\" to install ALCASAR ('su' command)"
        exit 0
fi
VERSION=`cat $DIR_INSTALL/VERSION`
usage="Usage: alcasar.sh {-i or --install} | {-u or --uninstall}"
nb_args=$#
args=$1
if [ $nb_args -eq 0 ]
then
        nb_args=1
        args="-h"
fi
chmod -R u+x $DIR_SCRIPTS/*
case $args in
        -\? | -h* | --h*)
                echo "$usage"
                exit 0
                ;;
        -i | --install)
                for func in license system_testing network_testing
                do
                        header_install
                        $func
                        if [ $DEBUG_ALCASAR == "on" ]
                        then
                                echo "*** 'debug' : end of function '$func' ***"
                                read
                        fi
                done
# RPMs install
                $DIR_SCRIPTS/alcasar-rpm.sh
                if [ "$?" != "0" ]
                then
                        exit 0
                fi
                if [ -e $CONF_FILE ]
                then
# Uninstall or update the running version
                        if [ "$mode" == "update" ]
                        then
                                $DIR_DEST_BIN/alcasar-uninstall.sh -update
                        else
                                $DIR_DEST_BIN/alcasar-uninstall.sh -full
                        fi
                fi
                if [ $DEBUG_ALCASAR == "on" ]
                then
                        echo "*** 'debug' : end of cleaning ***"
                        read
                fi
# Avoid some RPM automatic updates
                echo "/^kernel/" > /etc/urpmi/skip.list
                echo "/^wkhtmltopdf/" >> /etc/urpmi/skip.list
                echo "/^clamd/" >> /etc/urpmi/skip.list
                echo "/^clamav/" >> /etc/urpmi/skip.list
                echo "/^freeradius/" >> /etc/urpmi/skip.list
                if [ `egrep '^exclude=' /etc/dnf/dnf.conf |wc -l` -eq "1" ]; then
                        $SED "s?^exclude=.*?exclude=kernel\* wkhtmltopdf clamd clamav freeradius?g" /etc/dnf/dnf.conf
                else
                        echo "exclude=kernel* wkhtmltopdf clamd clamav freeradius" >> /etc/dnf/dnf.conf
                fi
# Test if conf file
                if [ -e /var/tmp/alcasar-conf.tar.gz ]
                then
# Extract some info from the previous configuration file
                        cd /var/tmp
                        tar -xf /var/tmp/alcasar-conf.tar.gz conf/etc/alcasar.conf
                        if [ "$mode" == "install" ] # don't display this if updating a running version
                        then
                                header_install
                                ORGANISME=`grep ^ORGANISM= conf/etc/alcasar.conf|cut -d"=" -f2`
                                PREVIOUS_VERSION=`grep ^VERSION= conf/etc/alcasar.conf|cut -d"=" -f2`
                                MAJ_PREVIOUS_VERSION=`echo $PREVIOUS_VERSION|cut -d"." -f1`
                                MIN_PREVIOUS_VERSION=`echo $PREVIOUS_VERSION|cut -d"." -f2`
                                UPD_PREVIOUS_VERSION=`echo $PREVIOUS_VERSION|cut -d"." -f3|cut -c1`
                                if [ $Lang == "fr" ]
                                        then echo "Le fichier de configuration d'une version $MAJ_PREVIOUS_VERSION.$MIN_PREVIOUS_VERSION.$UPD_PREVIOUS_VERSION a été trouvé";
                                        else echo "The configuration file of a version $MAJ_PREVIOUS_VERSION.$MIN_PREVIOUS_VERSION.$UPD_PREVIOUS_VERSION has been found";
                                fi
                                response=0
                                PTN='^[oOnNyY]?$'
                                until [[ "$response" =~ $PTN ]]
                                do
                                        if [ $Lang == "fr" ]
                                                then echo -n "Voulez-vous l'utiliser (O/n)? ";
                                                else echo -n "Do you want to use it (Y/n)?";
                                        fi
                                        read response
                                        if [ "$response" = "n" ] || [ "$response" = "N" ]
                                        then
                                                rm -f /var/tmp/alcasar-conf*
                                                rm -rf /var/tmp/conf
                                        fi
                                done
                        fi
                        cd $DIR_INSTALL
                fi
# Test if update
                if [ -e /var/tmp/alcasar-conf.tar.gz ]
                then
                        if [ $Lang == "fr" ]
                                then echo "#### Installation avec mise à jour ####";
                                else echo "#### Installation with update     ####";
                        fi
                        mode="update"
                fi
                for func in init network CA ACC time_server init_db freeradius chilli e2guardian antivirus ulogd nfsen vnstat dnsmasq unbound dhcpd BL cron fail2ban gammu_smsd msec letsencrypt mail_service post_install
                do
                        $func
                        if [ $DEBUG_ALCASAR == "on" ]
                        then
                                echo "*** 'debug' : end of function '$func' ***"
                                read
                        fi
                done
                ;;
        -u | --uninstall)
                if [ ! -e $DIR_DEST_BIN/alcasar-uninstall.sh ]
                then
                        if [ $Lang == "fr" ]
                                then echo "ALCASAR n'est pas installé!";
                                else echo "ALCASAR isn't installed!";
                        fi
                        exit 0
                fi
                response=0
                PTN='^[oOyYnN]?$'
                until [[ "$response" =~ $PTN ]]
                do
                        if [ $Lang == "fr" ]
                                then echo -n "Voulez-vous créer le fichier de configuration de la version actuelle (O/n)? ";
                                else echo -n "Do you want to create the running version configuration file (Y/n)? ";
                        fi
                        read response
                done
                if [ "$response" = "o" ] || [ "$response" = "O" ] || [ "$response" = "Y" ] || [ "$response" = "y" ]
                then
                        $DIR_SCRIPTS/alcasar-conf.sh --create
                else
                        rm -f /var/tmp/alcasar-conf*
                fi
# Uninstall the running version
                $DIR_DEST_BIN/alcasar-uninstall.sh -full
                ;;
        *)
                echo "Argument inconnu :$1";
                echo "Unknown argument :$1";
                echo "$usage"
                exit 1
                ;;
esac
# end of script

Generated by GNU Enscript 1.6.6.