Subversion Repositories ALCASAR

Rev

Rev 977 | Rev 990 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log

#!/bin/bash
#  $Id: alcasar.sh 978 2012-08-15 20:24:56Z franck $ 

# alcasar.sh

# ALCASAR - Portail captif d'accès à l'Internet -  Copyright (C) [2005] [ALcasar team - Rexy - 3abtux - ...] 
# Ce programme est un logiciel libre ; vous pouvez le redistribuer et/ou le modifier au titre des clauses de la Licence Publique Générale GNU, 
# elle que publiée par la Free Software Foundation ; soit la version 3 de la Licence. 
# Ce programme est distribué dans l'espoir qu'il sera utile, mais SANS AUCUNE GARANTIE ; 
# sans même une garantie implicite de COMMERCIABILITE ou DE CONFORMITE A UNE UTILISATION PARTICULIERE. 
# Voir la Licence Publique Générale GNU pour plus de détails. 
# Vous devriez avoir reçu un exemplaire de la Licence Publique Générale GNU avec ce programme ; 
# si ce n'est pas le cas, consultez :   <http://www.gnu.org/licenses/>.

#  team@alcasar.net

# by Franck BOUIJOUX, Pascal LEVANT and Richard REY
# This script is distributed under the Gnu General Public License (GPL)

# Script d'installation d'ALCASAR (Application Libre pour le Contrôle d'Accès Sécurisé et Authentifié au Réseau)
# ALCASAR est architecturé autour d'une distribution Linux Mandriva minimaliste et les logiciels libres suivants :
# Install script for ALCASAR (a secured and authenticated Internet access control captive portal)
# ALCASAR is based on a stripped Mandriva (LSB) with the following open source softwares :
#
# Coovachilli (a fork of chillispot), freeradius, mysql, apache, netfilter, squid, dansguardian, awstat, ntpd, openssl, dnsmasq, havp, libclamav  and firewalleyes

# Options :
#       -i or --install
#       -u or --uninstall

# Functions :
#       testing         : Tests de connectivité et de téléchargement avant installation
#       init            : Installation des RPM et des scripts
#       network         : Paramètrage du réseau
#       gestion         : Installation de l'interface de gestion
#       AC              : Initialisation de l'autorité de certification. Création des certificats
#       init_db         : Création de la base 'radius' sur le serveur MySql
#       param_radius    : Configuration du serveur d'authentification FreeRadius
#       param_web_radius: Configuration de l'interface de gestion de FreeRadius (dialupadmin)
#       param_chilli    : Configuration du daemon 'coova-chilli' et de la page d'authentification
#       param_squid     : Configuration du proxy squid en mode 'cache'
#       param_dansguardian : Configuration de l'analyseur de contenu DansGuardian
#       antivirus       : Installation havp + libclamav
#       param_awstats   : Configuration de l'interface des statistiques de consultation WEB
#       dnsmasq         : Configuration du serveur de noms et du serveur dhcp de secours
#       BL              : Configuration de la BlackList
#       cron            : Mise en place des exports de logs (+ chiffrement)
#       post_install    : Finalisation environnement ( sécurité, bannières, rotation logs, ...)

DATE=`date '+%d %B %Y - %Hh%M'`
DATE_SHORT=`date '+%d/%m/%Y'`
Lang=`echo $LANG|cut -c 1-2`
# ******* Files parameters - paramètres fichiers *********
DIR_INSTALL=`pwd`                               # install directory 
DIR_CONF="$DIR_INSTALL/conf"                    # répertoire d'installation contenant les fichiers de configuration
DIR_SCRIPTS="$DIR_INSTALL/scripts"              # répertoire d'installation contenant les scripts
DIR_SAVE="/var/Save"                            # répertoire de sauvegarde (system_backup, user_db_backup, logs)
DIR_WEB="/var/www/html"                         # répertoire racine APACHE
DIR_DG="/etc/dansguardian"                      # répertoire de config de DansGuardian
DIR_ACC="$DIR_WEB/acc"                          # répertoire du centre de gestion 'ALCASAR Control Center'
DIR_DEST_BIN="/usr/local/bin"                   # répertoire des scripts
DIR_DEST_SBIN="/usr/local/sbin"                 # répertoire des scripts d'admin
DIR_DEST_ETC="/usr/local/etc"                   # répertoire des fichiers de conf
CONF_FILE="$DIR_DEST_ETC/alcasar.conf"          # fichier de conf d'alcasar
PASSWD_FILE="/root/ALCASAR-passwords.txt"       # fichier texte contenant les mots de passe et secrets partagés 
# ******* DBMS parameters - paramètres SGBD ********
DB_RADIUS="radius"                              # nom de la base de données utilisée par le serveur FreeRadius
DB_USER="radius"                                # nom de l'utilisateur de la base de données
# ******* Network parameters - paramètres réseau *******
HOSTNAME="alcasar"                              # 
DOMAIN="localdomain"                            # domaine local
EXTIF="eth0"                                    # ETH0 est l'interface connectée à Internet (Box FAI)
INTIF="eth1"                                    # ETH1 est l'interface connectée au réseau local de consultation
DEFAULT_PRIVATE_IP_MASK="192.168.182.1/24"      # adresse d'ALCASAR (+masque) proposée par défaut sur le réseau de consultation
# ****** Paths - chemin des commandes *******
SED="/bin/sed -i"
# ****************** End of global parameters *********************

license ()
{
        if [ $Lang == "fr" ]
        then cat $DIR_INSTALL/gpl-3.0.fr.txt | more
        else cat $DIR_INSTALL/gpl-3.0.txt | more
        fi
        echo "Taper sur Entrée pour continuer !"
        echo "Enter to continue."
        read a
}

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 ()

##################################################################
##                      Fonction TESTING                        ##
## - Test de la connectivité Internet                          ##
##################################################################
testing ()
{
        if [ $Lang == "fr" ]
                then echo -n "Tests des paramètres réseau : "
                else echo -n "Network parameters tests : "
        fi
# We test eth0 config files
        PUBLIC_IP=`grep IPADDR /etc/sysconfig/network-scripts/ifcfg-$EXTIF|cut -d"=" -f2`
        PUBLIC_GATEWAY=`grep GATEWAY /etc/sysconfig/network-scripts/ifcfg-$EXTIF|cut -d"=" -f2`
        if [ `echo $PUBLIC_IP|wc -c` -lt 7 ] || [ `echo $PUBLIC_GATEWAY|wc -c` -lt 7 ]
                then
                if [ $Lang == "fr" ]
                then 
                        echo "É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 : 'service network restart'"
                else
                        echo "Failed"
                        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 'service network restart'"
                fi
                echo "DEVICE=$EXTIF"
                echo "IPADDR="
                echo "NETMASK="
                echo "GATEWAY="
                echo "DNS1="
                echo "DNS2="
                echo "ONBOOT=yes"
                exit 0
        fi
        echo -n "."
# We test the Ethernet links state
        for i in $EXTIF $INTIF
        do
                /sbin/ip link set $i up
                sleep 3
                CMD=`/usr/sbin/ethtool $i |grep Link | awk '{print $NF}'`
                CMD2=`/sbin/mii-tool $i | grep -i link | awk '{print $NF}'`
                if [ $CMD != "yes" ] && [ $CMD2 != "ok" ]
                        then
                        if [ $Lang == "fr" ]
                        then 
                                echo "Échec"
                                echo "Le lien réseau de la carte $i n'est pas actif."
                                echo "Réglez ce problème puis relancez ce script."
                        else
                                echo "Failed"
                                echo "The link state of $i interface id down."
                                echo "Resolv this problem, then restart this script."
                        fi
                        exit 0
                fi
        echo -n "."
        done
# On teste la présence d'un routeur par défaut (Box FAI)
        if [ `ip route list|grep -c ^default` -ne "1" ] ; then
                if [ $Lang == "fr" ]
                then 
                        echo "Échec"
                        echo "Vous n'avez pas configuré l'accès à Internet ou le câble réseau n'est pas sur la bonne carte."
                        echo "Réglez ce problème puis relancez ce script."
                else
                        echo "Failed"
                        echo "You haven't configured Internet access or Internet link is on the wrong Ethernet card"
                        echo "Resolv this problem, then restart this script."
                fi
                exit 0
        fi
        echo -n "."
# On traite le cas où l'interface configurée lors de l'installation est "eth1" au lieu de "eth0" (mystère sur certaines versions de BIOS et de VirtualBox)
        if [ `ip route list|grep ^default|grep -c eth1` -eq "1" ] ; then
                if [ $Lang == "fr" ]
                        then echo "La configuration des cartes réseau va être corrigée."
                        else echo "The Ethernet card configuration will be corrected."
                fi
                /etc/init.d/network stop
                mv -f /etc/sysconfig/network-scripts/ifcfg-eth1 /etc/sysconfig/network-scripts/ifcfg-eth0
                $SED "s?eth1?eth0?g" /etc/sysconfig/network-scripts/ifcfg-eth0
                /etc/init.d/network start
                echo 0 > /proc/sys/net/ipv4/conf/all/log_martians
                sleep 2
                if [ $Lang == "fr" ]
                        then echo "Configuration corrigée"
                        else echo "Configuration updated"
                fi
                sleep 2
                if [ $Lang == "fr" ]
                        then echo "Vous pouvez relancer ce script."
                        else echo "You can restart this script."
                fi
                exit 0
        fi
        echo -n "."
# On teste le lien vers le routeur par defaut
        IP_GW=`ip route list|grep ^default|cut -d" " -f3`
        arp_reply=`/usr/sbin/arping -b -I$EXTIF -c1 -w2 $IP_GW|grep response|cut -d" " -f2`
        if [ $(expr $arp_reply) -eq 0 ]
                then
                if [ $Lang == "fr" ]
                then 
                        echo "Échec"
                        echo "Le routeur de site ou la Box Internet ($IP_GW) ne répond pas."
                        echo "Réglez ce problème puis relancez ce script."
                else
                        echo "Failed"
                        echo "The Internet gateway doesn't answered"
                        echo "Resolv this problem, then restart this script."
                fi
                exit 0
        fi
        echo -n "."
# On teste la connectivité Internet
        rm -rf /tmp/con_ok.html
        /usr/bin/curl www.google.fr -s -o /tmp/con_ok.html
        if [ ! -e /tmp/con_ok.html ]
        then
                if [ $Lang == "fr" ]
                then 
                        echo "La tentative de connexion vers Internet a échoué (google.fr)."
                        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 "The Internet connection try failed (google.fr)."
                        echo "Please, verify that the $EXTIF card is connected with the Internet gateway."
                        echo "Verify the DNS IP addresses"
                fi
                exit 0
        fi
        rm -rf /tmp/con_ok.html
        echo ". : ok"
} # end of testing

##################################################################
##                      Fonction INIT                           ##
## - Création du fichier "/root/ALCASAR_parametres.txt"                ##
## - Installation et modification des scripts du portail        ##
##################################################################
init ()
{
        if [ "$mode" != "update" ]
        then
# On affecte le nom d'organisme
                header_install
                ORGANISME=!
                PTN='^[a-zA-Z0-9-]*$'
                until [[ $(expr $ORGANISME : $PTN) -gt 0 ]]
                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
        rm -f $PASSWD_FILE
        grubpwd=`cat /dev/urandom | tr -dc [:alnum:] | head -c8`        # mot de passe de protection du menu Grub
        echo -n "Password to protect the boot menu (GRUB) : " > $PASSWD_FILE
        echo "$grubpwd" >> $PASSWD_FILE
        md5_grubpwd=`/usr/bin/md5pass $grubpwd`
        $SED "/^password.*/d" /boot/grub/menu.lst
        $SED "1ipassword --md5 $md5_grubpwd" /boot/grub/menu.lst
        mysqlpwd=`cat /dev/urandom | tr -dc [:alnum:] | head -c8`       # mot de passe de l'administrateur Mysqld
        echo -n "Name and password of MYSQL administrator : " >> $PASSWD_FILE
        echo "root / $mysqlpwd" >> $PASSWD_FILE
        radiuspwd=`cat /dev/urandom | tr -dc [:alnum:] | head -c8`      # mot de passe de l'utilisateur Mysqld (utilisé par freeradius)
        echo -n "Name and password of MYSQL user : " >> $PASSWD_FILE
        echo "$DB_USER / $radiuspwd" >> $PASSWD_FILE
        secretuam=`cat /dev/urandom | tr -dc [:alnum:] | head -c8`      # secret partagé entre intercept.php et coova-chilli
        echo -n "Shared secret between the script 'intercept.php' and coova-chilli : " >> $PASSWD_FILE
        echo "$secretuam" >> $PASSWD_FILE
        secretradius=`cat /dev/urandom | tr -dc [:alnum:] | head -c8`   # secret partagé entre coova-chilli et FreeRadius
        echo -n "Shared secret between coova-chilli and FreeRadius : " >> $PASSWD_FILE
        echo "$secretradius" >> $PASSWD_FILE
        chmod 640 $PASSWD_FILE
# Scripts and conf files copy 
#  - in /usr/local/bin :  alcasar-{CA.sh,conf.sh,import-clean.sh,iptables-bypass.sh,iptables.sh,log.sh,watchdog.sh}
        cp -f $DIR_SCRIPTS/alcasar* $DIR_DEST_BIN/. ; chown root:root $DIR_DEST_BIN/alcasar* ; chmod 740 $DIR_DEST_BIN/alcasar*
#  - in /usr/local/sbin :  alcasar-{bl.sh,bypass.sh,dateLog.sh,havp.sh,logout.sh,mysql.sh,nf.sh,profil.sh,uninstall.sh,version-list.sh,load-balancing.sh}
        cp -f $DIR_SCRIPTS/sbin/alcasar* $DIR_DEST_SBIN/. ; chown root:root $DIR_DEST_SBIN/alcasar* ; chmod 740 $DIR_DEST_SBIN/alcasar*
#  - in /usr/local/etc : alcasar-{bl-categories-enabled,dns-name,iptables-local.sh,services}
        cp -f $DIR_CONF/etc/alcasar* $DIR_DEST_ETC/. ; chown root:apache $DIR_DEST_ETC/alcasar* ; chmod 660 $DIR_DEST_ETC/alcasar*
        $SED "s?^radiussecret.*?radiussecret=\"$secretradius\"?g" $DIR_DEST_SBIN/alcasar-logout.sh
        $SED "s?^DB_RADIUS=.*?DB_RADIUS=\"$DB_RADIUS\"?g" $DIR_DEST_SBIN/alcasar-mysql.sh
        $SED "s?^DB_USER=.*?DB_USER=\"$DB_USER\"?g" $DIR_DEST_SBIN/alcasar-mysql.sh $DIR_DEST_BIN/alcasar-conf.sh
        $SED "s?^radiuspwd=.*?radiuspwd=\"$radiuspwd\"?g" $DIR_DEST_SBIN/alcasar-mysql.sh $DIR_DEST_BIN/alcasar-conf.sh
# generate central conf file
        cat <<EOF > $CONF_FILE
##########################################
##                                      ##
##          ALCASAR Parameters          ##
##                                      ##
##########################################

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

##################################################################
##                      Fonction network                        ##
## - Définition du plan d'adressage du réseau de consultation ##
## - Nommage DNS du système                                    ##
## - Configuration de l'interface eth1 (réseau de consultation)        ##
## - Modification du fichier /etc/hosts                         ##
## - Configuration du serveur de temps (NTP)                    ##
## - Renseignement des fichiers hosts.allow et hosts.deny       ##
##################################################################
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 [[ $(expr $response : $PTN) -gt 0 ]]
                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 conf/etc/alcasar.conf|cut -d"=" -f2` 
                rm -rf conf/etc/alcasar.conf
        fi
# Define LAN side global parameters
        hostname $HOSTNAME
        PRIVATE_NETWORK=`/bin/ipcalc -n $PRIVATE_IP_MASK | cut -d"=" -f2`                               # private network address (ie.: 192.168.182.0)
        PRIVATE_NETMASK=`/bin/ipcalc -m $PRIVATE_IP_MASK | cut -d"=" -f2`                               # private network mask (ie.: 255.255.255.0)
        PRIVATE_IP=`echo $PRIVATE_IP_MASK | cut -d"/" -f1`                                              # ALCASAR private ip address (consultation LAN side)
        PRIVATE_PREFIX=`/bin/ipcalc -p $PRIVATE_IP_MASK |cut -d"=" -f2`                                 # network prefix (ie. 24)
        PRIVATE_NETWORK_MASK=$PRIVATE_NETWORK/$PRIVATE_PREFIX                                           # ie.: 192.168.182.0/24
        classe=$((PRIVATE_PREFIX/8)); classe_sup=`expr $classe + 1`; classe_sup_sup=`expr $classe + 2`  # 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_BROADCAST=`/bin/ipcalc -b $PRIVATE_NETWORK_MASK | cut -d"=" -f2`                        # private network broadcast (ie.: 192.168.182.255)
        private_network_ending=`echo $PRIVATE_NETWORK | cut -d"." -f$classe_sup`                        # last octet of LAN address
        private_broadcast_ending=`echo $PRIVATE_BROADCAST | cut -d"." -f$classe_sup`                    # last octet of LAN broadcast
        PRIVATE_FIRST_IP=`echo $PRIVATE_NETWORK | cut -d"." -f1-3`"."`expr $private_network_ending + 1`         # First network address (ex.: 192.168.182.1)
        PRIVATE_SECOND_IP=`echo $PRIVATE_NETWORK | cut -d"." -f1-3`"."`expr $private_network_ending + 2`        # second network address (ex.: 192.168.182.2)
        PRIVATE_LAST_IP=`echo $PRIVATE_BROADCAST | cut -d"." -f1-3`"."`expr $private_broadcast_ending - 1`      # last network address (ex.: 192.168.182.254)
        PRIVATE_MAC=`/sbin/ip link show $INTIF | grep ether | cut -d" " -f6`                            # MAC address of INTIF (eth1)
# Define Internet parameters
        [ -e /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF ] || cp /etc/sysconfig/network-scripts/ifcfg-$EXTIF /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF
        DNS1=`grep DNS1 /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF|cut -d"=" -f2`      # @ip 1er DNS
        DNS2=`grep DNS2 /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF|cut -d"=" -f2`      # @ip 2ème DNS
        DNS1=${DNS1:=208.67.220.220}
        DNS2=${DNS2:=208.67.222.222}
        PUBLIC_NETMASK=`grep NETMASK /etc/sysconfig/network-scripts/default-ifcfg-$EXTIF|cut -d"=" -f2`
        DEFAULT_PUBLIC_NETMASK=`ipcalc -m 192.168.182.2 | cut -d"=" -f2`
        PUBLIC_NETMASK=${PUBLIC_NETMASK:=$DEFAULT_PUBLIC_NETMASK}
        PUBLIC_PREFIX=`/bin/ipcalc -p 192.168.182.2 $PUBLIC_NETMASK|cut -d"=" -f2`

        echo "PUBLIC_IP=$PUBLIC_IP/$PUBLIC_PREFIX" >> $CONF_FILE
        echo "PUBLIC_MTU=1500" >> $CONF_FILE
        echo "GW=$PUBLIC_GATEWAY" >> $CONF_FILE 
        echo "DNS1=$DNS1" >> $CONF_FILE
        echo "DNS2=$DNS2" >> $CONF_FILE
        echo "PRIVATE_IP=$PRIVATE_IP_MASK" >> $CONF_FILE
        echo "DHCP=full" >> $CONF_FILE
        echo "EXT_DHCP_IP=none" >> $CONF_FILE
        echo "RELAY_DHCP_IP=none" >> $CONF_FILE
        echo "RELAY_DHCP_PORT=none" >> $CONF_FILE
        [ -e /etc/sysconfig/network.default ] || cp /etc/sysconfig/network /etc/sysconfig/network.default
# config network
        cat <<EOF > /etc/sysconfig/network
NETWORKING=yes
HOSTNAME="$HOSTNAME"
FORWARD_IPV4=true
EOF
# config /etc/hosts
        [ -e /etc/hosts.default ] || cp /etc/hosts /etc/hosts.default
        cat <<EOF > /etc/hosts
127.0.0.1       localhost
$PRIVATE_IP     $HOSTNAME $HOSTNAME.$DOMAIN
EOF
# Config eth0 (Internet)
        cat <<EOF > /etc/sysconfig/network-scripts/ifcfg-$EXTIF
DEVICE=$EXTIF
BOOTPROTO=static
IPADDR=$PUBLIC_IP
NETMASK=$PUBLIC_NETMASK
GATEWAY=$PUBLIC_GATEWAY
DNS1=127.0.0.1
ONBOOT=yes
METRIC=10
NOZEROCONF=yes
MII_NOT_SUPPORTED=yes
IPV6INIT=no
IPV6TO4INIT=no
ACCOUNTING=no
USERCTL=no
EOF
# Config eth1 (consultation LAN) in normal mode
        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
# Config of eth1 in bypass mode (see "alcasar-bypass.sh")
        cat <<EOF > /etc/sysconfig/network-scripts/default-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
# Mise à l'heure du serveur
        [ -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
# Configuration du serveur de temps (sur lui même)
        [ -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
EOF

        chown -R ntp:ntp /var/lib/ntp
# Renseignement des fichiers hosts.allow et 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
# Firewall config
        $SED "s?^EXTIF=.*?EXTIF=\"$EXTIF\"?g" $DIR_DEST_BIN/alcasar-iptables.sh  $DIR_DEST_BIN/alcasar-iptables-bypass.sh
        $SED "s?^INTIF=.*?INTIF=\"$INTIF\"?g" $DIR_DEST_BIN/alcasar-iptables.sh  $DIR_DEST_BIN/alcasar-iptables-bypass.sh
        chmod o+r $DIR_DEST_BIN/alcasar-iptables.sh #lecture possible pour apache (interface php du filtrage réseau)
# create the filter exception file and ip_bloqued file
        touch $DIR_DEST_ETC/alcasar-filter-exceptions
# create the ip_blocked file with a first line (LAN between ALCASAR and the Internet GW)
        echo "#$PUBLIC_IP/$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 "ip_conntrack_ftp" >>  /etc/modprobe.preload
# the script "$DIR_DEST_BIN/alcasar-iptables.sh" is launched at the end in order to allow update via ssh
} # End of network ()

##################################################################
##                      Fonction gestion                        ##
## - installation du centre de gestion                          ##
## - configuration du serveur web (Apache)                      ##
## - définition du 1er comptes de gestion                      ##
## - sécurisation des accès                                   ##
##################################################################
gestion()
{
        [ -d $DIR_WEB ] && rm -rf $DIR_WEB
        mkdir $DIR_WEB
# Copie et configuration des fichiers du centre de gestion
        cp -rf $DIR_INSTALL/web/* $DIR_WEB/
        echo "$VERSION" > $DIR_WEB/VERSION
        $SED "s?99/99/9999?$DATE_SHORT?g" $DIR_ACC/menu.php
        $SED "s?\$DB_RADIUS = .*?\$DB_RADIUS = \"$DB_RADIUS\"\;?g" $DIR_ACC/phpsysinfo/includes/xml/portail.php
        $SED "s?\$DB_USER = .*?\$DB_USER = \"$DB_USER\"\;?g" $DIR_ACC/phpsysinfo/includes/xml/portail.php
        $SED "s?\$radiuspwd = .*?\$radiuspwd = \"$radiuspwd\"\;?g" $DIR_ACC/phpsysinfo/includes/xml/portail.php
        $SED "s?\$hostname =.*?\$hostname = \"$HOSTNAME\";?g" $DIR_WEB/index.php
        chmod 640 $DIR_ACC/phpsysinfo/includes/xml/portail.php
        chown -R apache:apache $DIR_WEB/*
        for i in system_backup base logs/firewall logs/httpd logs/squid logs/security;
        do
                [ -d $DIR_SAVE/$i ] || mkdir -p $DIR_SAVE/$i
        done
        chown -R root:apache $DIR_SAVE
# Configuration et sécurisation php
        [ -e /etc/php.ini.default ] || cp /etc/php.ini /etc/php.ini.default
        timezone=`cat /etc/sysconfig/clock|grep ZONE|cut -d"=" -f2`
        $SED "s?^;date.timezone =.*?date.timezone = $timezone?g" /etc/php.ini
        $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?^html_errors.*?html_errors = Off?g" /etc/php.ini
        $SED "s?^expose_php.*?expose_php = Off?g" /etc/php.ini
# Configuration et sécurisation Apache
        rm -rf /var/www/cgi-bin/* /var/www/perl/* /var/www/icons/README* /var/www/error/README*
        [ -e /etc/httpd/conf/httpd.conf.default ] || cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.default
        $SED "s?^#ServerName.*?ServerName $HOSTNAME?g" /etc/httpd/conf/httpd.conf
        $SED "s?^Listen.*?Listen $PRIVATE_IP:80?g" /etc/httpd/conf/httpd.conf
        $SED "s?^ServerTokens.*?ServerTokens Prod?g" /etc/httpd/conf/httpd.conf
        $SED "s?^ServerSignature.*?ServerSignature Off?g" /etc/httpd/conf/httpd.conf
        $SED "s?^#ErrorDocument 404 /missing.html.*?ErrorDocument 404 /index.html?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule authn_anon_module.*?#LoadModule authn_anon_module modules/mod_authn_anon.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule status_module.*?#LoadModule status_module modules/mod_status.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule autoindex_module.*?#LoadModule autoindex_module modules/mod_autoindex.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule info_module.*?#LoadModule info_module modules/mod_info.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule imagemap_module.*?#LoadModule imagemap_module modules/mod_imagemap.so?g" /etc/httpd/conf/httpd.conf
        $SED "s?^LoadModule rewrite_module.*?#LoadModule rewrite_module modules/mod_rewrite.so?g" /etc/httpd/conf/httpd.conf
        FIC_MOD_SSL=`find /etc/httpd/modules.d/ -type f -name *mod_ssl.conf`
        $SED "s?^Listen.*?Listen $PRIVATE_IP:443?g" $FIC_MOD_SSL # On écoute en SSL que sur INTIF
        $SED "s?background-color.*?background-color: #EFEFEF; }?g" /var/www/error/include/top.html
        [ -e /var/www/error/include/bottom.html.default ] || mv /var/www/error/include/bottom.html /var/www/error/include/bottom.html.default
        cat <<EOF > /var/www/error/include/bottom.html
</body>
</html>
EOF
# Définition du premier compte lié au profil 'admin'
        header_install
        if [ "$mode" = "install" ]
        then
                admin_portal=!
                PTN='^[a-zA-Z0-9-]*$'
                until [[ $(expr $admin_portal : $PTN) -gt 0 ]]
                        do
                        header_install
                        if [ $Lang == "fr" ]
                        then 
                                echo ""
                                echo "Définissez un premier compte d'administration du portail :"
                                echo
                                echo -n "Nom : "
                        else
                                echo ""
                                echo "Define the first account allow to administrate the portal :"
                                echo
                                echo -n "Account : "
                        fi
                        read admin_portal
                        if [ "$admin_portal" == "" ]
                                then
                                admin_portal=!
                        fi
                        done
# Création du fichier de clés de ce compte dans le profil "admin"
                [ -d $DIR_DEST_ETC/digest ] && rm -rf $DIR_DEST_ETC/digest
                mkdir -p $DIR_DEST_ETC/digest
                chmod 755 $DIR_DEST_ETC/digest
                until [ -s $DIR_DEST_ETC/digest/key_admin ]
                        do
                                /usr/sbin/htdigest -c $DIR_DEST_ETC/digest/key_admin $HOSTNAME $admin_portal
                        done
                $DIR_DEST_SBIN/alcasar-profil.sh --list
        else   # mise à jour des versions < 2.1
                if ([ $MAJ_RUNNING_VERSION -lt 2 ] || ([ $MAJ_RUNNING_VERSION -eq 2 ] && [ $MIN_RUNNING_VERSION -lt 1 ]))
                        then
                        if [ $Lang == "fr" ]
                        then 
                                echo "Cette mise à jour nécessite de redéfinir le premier compte d'administration du portail"
                                echo
                                echo -n "Nom : "
                        else
                                echo "This update need to redefine the first admin account"
                                echo
                                echo -n "Account : "
                        fi
                        read admin_portal
                        [ -d $DIR_DEST_ETC/digest ] && rm -rf $DIR_DEST_ETC/digest
                        mkdir -p $DIR_DEST_ETC/digest
                        chmod 755 $DIR_DEST_ETC/digest
                        until [ -s $DIR_DEST_ETC/digest/key_admin ]
                        do
                                /usr/sbin/htdigest -c $DIR_DEST_ETC/digest/key_admin $HOSTNAME $admin_portal
                        done
                        $DIR_DEST_SBIN/alcasar-profil.sh --list
                fi
        fi
# synchronisation horaire
        ntpd -q -g &
# Sécurisation du centre
        rm -f /etc/httpd/conf/webapps.d/*
        cat <<EOF > /etc/httpd/conf/webapps.d/alcasar.conf
<Directory $DIR_ACC>
        SSLRequireSSL
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On
        AuthUserFile $DIR_DEST_ETC/digest/key_all
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
<Directory $DIR_ACC/admin>
        SSLRequireSSL
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On
        AuthUserFile $DIR_DEST_ETC/digest/key_admin
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
<Directory $DIR_ACC/manager>
        SSLRequireSSL
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On
        AuthUserFile $DIR_DEST_ETC/digest/key_manager
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
<Directory $DIR_ACC/backup>
        SSLRequireSSL
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On
        AuthUserFile $DIR_DEST_ETC/digest/key_backup
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
Alias /save/ "$DIR_SAVE/"
<Directory $DIR_SAVE>
        SSLRequireSSL
        Options Indexes
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        AuthUserFile $DIR_DEST_ETC/digest/key_backup
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
EOF
} # End of gestion ()

##########################################################################################
##                              Fonction AC()                                           ##
## - Création d'une Autorité de Certification et du certificat serveur pour apache    ##
##########################################################################################
AC ()
{
        $SED "s?ifcfg-eth.?ifcfg-$INTIF?g" $DIR_DEST_BIN/alcasar-CA.sh
        $DIR_DEST_BIN/alcasar-CA.sh
        FIC_VIRTUAL_SSL=`find /etc/httpd/conf -type f -name *default_ssl_vhost.conf`
        [ -e /etc/httpd/conf/vhosts-ssl.default ]  || cp $FIC_VIRTUAL_SSL /etc/httpd/conf/vhosts-ssl.default
        $SED "s?localhost.crt?alcasar.crt?g" $FIC_VIRTUAL_SSL
        $SED "s?localhost.key?alcasar.key?g" $FIC_VIRTUAL_SSL
        $SED "s?^#SSLCertificateChainFile.*?SSLCertificateChainFile /etc/pki/tls/certs/server-chain.crt?" $FIC_VIRTUAL_SSL
        chown -R root:apache /etc/pki
        chmod -R 750 /etc/pki
} # End AC ()

##########################################################################################
##                      Fonction init_db()                                              ##
## - Initialisation de la base Mysql                                                    ##
## - Affectation du mot de passe de l'administrateur (root)                             ##
## - Suppression des bases et des utilisateurs superflus                                ##
## - Création de la base 'radius'                                                      ##
## - Installation du schéma de cette base                                              ##
## - Import des tables de comptabilité (mtotacct, totacct) et info_usagers (userinfo)  ##
##       ces table proviennent de 'dialupadmin' (paquetage freeradius-web)              ##
##########################################################################################
init_db ()
{
        mkdir -p /var/lib/mysql/.tmp
        chown mysql:mysql /var/lib/mysql/.tmp
        [ -e /etc/my.cnf.rpmnew ] && mv /etc/my.cnf.rpmnew /etc/my.cnf          # prend en compte les migrations de MySQL
        [ -e /etc/my.cnf.default ] || cp /etc/my.cnf /etc/my.cnf.default
        $SED "s?^#bind-address.*?bind-address=127.0.0.1?g" /etc/my.cnf
        /etc/init.d/mysqld start
        sleep 4
        mysqladmin -u root password $mysqlpwd
        MYSQL="/usr/bin/mysql -uroot -p$mysqlpwd --exec"
# Delete exemple databases if exist
        $MYSQL="DROP DATABASE IF EXISTS test;DROP DATABASE IF EXISTS tmp;CONNECT mysql;DELETE from user where user='';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
        mysql -u$DB_USER -p$radiuspwd $DB_RADIUS < $DIR_CONF/radiusd-db-vierge.sql
# modify the start script in order to close accounting connexion when the system is comming down or up
        [ -e /etc/init.d/mysqld.default ] || cp /etc/init.d/mysqld /etc/init.d/mysqld.default
        $SED "/wait_for_pid created/a echo \"Flush ALCASAR open accounting sessions\"; /usr/local/sbin/alcasar-mysql.sh -acct_stop" /etc/init.d/mysqld
        $SED "/'stop')/a echo \"Flush ALCASAR open accounting sessions\"; /usr/local/sbin/alcasar-mysql.sh -acct_stop" /etc/init.d/mysqld
} # End init_db ()

##########################################################################
##                      Fonction param_radius                           ##
## - Paramètrage des fichiers de configuration FreeRadius              ##
## - Affectation du secret partagé entre coova-chilli et freeradius    ##
## - Modification de fichier de conf pour l'accès à Mysql             ##
##########################################################################
param_radius ()
{
        cp -f $DIR_CONF/radiusd-db-vierge.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
# paramètrage 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
# suppression de la fonction proxy
        $SED "s?^[\t ]*proxy_requests.*?proxy_requests = no?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*\$INCLUDE proxy.conf.*?#\$INCLUDE proxy.conf?g" /etc/raddb/radiusd.conf
# suppression du module EAP
        $SED "s?^[\t ]*\$INCLUDE eap.conf.*?#\$INCLUDE eap.conf?g" /etc/raddb/radiusd.conf
# écoute sur loopback uniquement (à modifier plus tard pour l'EAP)
        $SED "s?^[\t ]*ipaddr =.*?ipaddr = 127.0.0.1?g" /etc/raddb/radiusd.conf
# prise en compte du module SQL et des compteurs SQL
        $SED "s?^[\t ]*#[\t ]*\$INCLUDE sql.conf.*?\$INCLUDE sql.conf?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*#[\t ]*\$INCLUDE sql/mysql/counter.conf?\$INCLUDE sql/mysql/counter.conf?g" /etc/raddb/radiusd.conf
        $SED "s?^[\t ]*\$INCLUDE policy.conf?#\$INCLUDE policy.conf?g" /etc/raddb/radiusd.conf
# purge du répertoire des serveurs virtuels et copie du fichier de configuration d'Alcasar
        rm -f /etc/raddb/sites-enabled/*
        cp $DIR_CONF/alcasar-radius /etc/raddb/sites-available/alcasar
        chown radius:apache /etc/raddb/sites-available/alcasar /etc/raddb/modules/ldap # droits rw pour apache (module ldap)
        chmod 660 /etc/raddb/sites-available/alcasar /etc/raddb/modules/ldap
        chgrp apache /etc/raddb /etc/raddb/sites-available /etc/raddb/modules
        ln -s /etc/raddb/sites-available/alcasar /etc/raddb/sites-enabled/alcasar
# Inutile dans notre fonctionnement mais les liens sont recréés par un update de radius ... donc forcé en tant que fichier à 'vide'
        touch /etc/raddb/sites-enabled/{inner-tunnel,control-socket,default}
# configuration du fichier client.conf (127.0.0.1 suffit mais on laisse le deuxième client pour la future gestion de l'EAP)
        [ -e /etc/raddb/clients.conf.default ] || cp -f /etc/raddb/clients.conf /etc/raddb/clients.conf.default
        cat << EOF > /etc/raddb/clients.conf
client 127.0.0.1 {
        secret = $secretradius
        shortname = localhost
}
EOF
# modif sql.conf
        [ -e /etc/raddb/sql.conf.default ] || cp /etc/raddb/sql.conf /etc/raddb/sql.conf.default
        $SED "s?^[\t ]*login =.*?login = \"$DB_USER\"?g" /etc/raddb/sql.conf
        $SED "s?^[\t ]*password =.*?password = \"$radiuspwd\"?g" /etc/raddb/sql.conf
        $SED "s?^[\t ]*radius_db =.*?radius_db = \"$DB_RADIUS\"?g" /etc/raddb/sql.conf
        $SED "s?^[\t ]*sqltrace =.*?sqltrace = no?g" /etc/raddb/sql.conf
# modif dialup.conf
        [ -e /etc/raddb/sql/mysql/dialup.conf.default ] || cp /etc/raddb/sql/mysql/dialup.conf /etc/raddb/sql/mysql/dialup.conf.default
        cp -f $DIR_CONF/dialup.conf /etc/raddb/sql/mysql/dialup.conf
} # End param_radius ()

##########################################################################
##                      Fonction param_web_radius                       ##
## - Import, modification et paramètrage de l'interface "dialupadmin"  ##
## - Création du lien vers la page de changement de mot de passe        ##
##########################################################################
param_web_radius ()
{
# copie de l'interface d'origine dans la structure Alcasar
        [ -d /usr/share/freeradius-web ] && cp -rf /usr/share/freeradius-web/* $DIR_ACC/manager/
        rm -f $DIR_ACC/manager/index.html $DIR_ACC/manager/readme 
        rm -f $DIR_ACC/manager/htdocs/about.html $DIR_ACC/manager/htdocs/index.html $DIR_ACC/manager/htdocs/content.html
# copie des fichiers modifiés
        cp -rf $DIR_INSTALL/web/acc/manager/* $DIR_ACC/manager/
        chown -R apache:apache $DIR_ACC/manager/
# Modification des fichiers de configuration
        [ -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
        $SED "s?^sql_debug:.*?sql_debug: false?g" /etc/freeradius-web/admin.conf
        $SED "s?^sql_usergroup_table: .*?sql_usergroup_table: radusergroup?g" /etc/freeradius-web/admin.conf
        $SED "s?^sql_password_attribute:.*?sql_password_attribute: Crypt-Password?g" /etc/freeradius-web/admin.conf
        $SED "s?^general_finger_type.*?# general_finger_type: snmp?g" /etc/freeradius-web/admin.conf
        $SED "s?^general_stats_use_totacct.*?general_stats_use_totacct: yes?g" /etc/freeradius-web/admin.conf
        $SED "s?^general_charset.*?general_charset: utf-8?g" /etc/freeradius-web/admin.conf
        [ -e /etc/freeradius-web/config.php.default ] || cp /etc/freeradius-web/config.php /etc/freeradius-web/config.php.default
        cp -f $DIR_CONF/freeradiusweb-config.php /etc/freeradius-web/config.php
        cat <<EOF > /etc/freeradius-web/naslist.conf
nas1_name: alcasar-$ORGANISME
nas1_model: Portail captif
nas1_ip: $PRIVATE_IP
nas1_port_num: 0
nas1_community: public
EOF
# Modification des attributs visibles lors de la création d'un usager ou d'un groupe
        [ -e /etc/freeradius-web/user_edit.attrs.default ] || mv /etc/freeradius-web/user_edit.attrs /etc/freeradius-web/user_edit.attrs.default
        cp -f $DIR_CONF/user_edit.attrs /etc/freeradius-web/user_edit.attrs
# Ajout du mappage des attributs chillispot
        [ -e /etc/freeradius-web/sql.attrmap.default ] || mv /etc/freeradius-web/sql.attrmap /etc/freeradius-web/sql.attrmap.default
        cp -f $DIR_CONF/sql.attrmap /etc/freeradius-web/sql.attrmap
# Modification des attributs visibles sur les pages des statistiques (suppression NAS_IP et NAS_port)
        [ -e /etc/freeradius-web/sql.attrs.default ] || cp /etc/freeradius-web/sql.attrs /etc/freeradius-web/user_edit.attrs.default
        $SED "s?^NASIPAddress.*?NASIPAddress\tNas IP Address\tno?g" /etc/freeradius-web/sql.attrs
        $SED "s?^NASPortId.*?NASPortId\tNas Port\tno?g" /etc/freeradius-web/sql.attrs
        chown -R apache:apache /etc/freeradius-web
# Ajout de l'alias vers la page de "changement de mot de passe usager"
        cat <<EOF >> /etc/httpd/conf/webapps.d/alcasar.conf
<Directory $DIR_WEB/pass>
        SSLRequireSSL
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
        ErrorDocument 404 https://$HOSTNAME
</Directory>
EOF
} # End of param_web_radius ()

##################################################################################
##                      Fonction param_chilli                                   ##
## - Création du fichier d'initialisation et de configuration de coova-chilli  ##
## - Paramètrage de la page d'authentification (intercept.php)                 ##
##################################################################################
param_chilli ()
{
# init file creation
        [ -e /etc/init.d/chilli.default ] || cp /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=/var/run/chilli.pid
[ -f \$CONFIG ] || {
    echo "\$CONFIG Not found"
    exit 0
}
RETVAL=0
prog="chilli"
case \$1 in
    start)
        if [ -f \$pidfile ] ; then 
                gprintf "chilli is already running"
        else
                gprintf "Starting \$prog: "
                rm -f /var/run/chilli* # cleaning
                /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 eth1 0.0.0.0
                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
        else    
                gprintf "chilli is not running"
        fi
        ;;
    
    *)
        echo "Usage: \$0 {start|stop|restart|reload|status}"
        exit 1
esac
echo
EOF

# conf file creation
        [ -e /etc/chilli.conf.default ] || cp /etc/chilli.conf /etc/chilli.conf.default
        cat <<EOF > /etc/chilli.conf
# coova config for ALCASAR
cmdsocket       /var/run/chilli.sock
unixipc         chilli.eth1.ipc
pidfile         /var/run/chilli.eth1.pid
net             $PRIVATE_NETWORK_MASK
dhcpif          $INTIF
ethers          $DIR_DEST_ETC/alcasar-ethers
#nodynip
#statip
dynip           $PRIVATE_NETWORK_MASK
domain          localdomain
dns1            $PRIVATE_IP
dns2            $PRIVATE_IP
uamlisten       $PRIVATE_IP
uamport         3990
macauth
macpasswd       password
locationname    $HOSTNAME
radiusserver1   127.0.0.1
radiusserver2   127.0.0.1
radiussecret    $secretradius
radiusauthport  1812
radiusacctport  1813
uamserver       https://$HOSTNAME/intercept.php
radiusnasid     $HOSTNAME
uamsecret       $secretuam
uamallowed      alcasar
coaport         3799
include         $DIR_DEST_ETC/alcasar-uamallowed
include         $DIR_DEST_ETC/alcasar-uamdomain
#dhcpgateway
#dhcprelayagent
#dhcpgatewayport
EOF
# create file for DHCP static ip. Reserve the second IP address for eth1 (the first one is for tun0)
        echo "$PRIVATE_MAC $PRIVATE_SECOND_IP" > $DIR_DEST_ETC/alcasar-ethers
# 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
        $SED "s?^\$userpassword=1.*?\$userpassword=1;?g" $DIR_WEB/intercept.php
# user 'chilli' creation (in order to run conup/off and up/down scripts
        chilli_exist=`grep chilli /etc/passwd|wc -l`
        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 param_chilli ()

##########################################################
##                      Fonction param_squid            ##
## - Paramètrage du proxy 'squid' en mode 'cache'      ##
## - Initialisation de la base de données              ##
##########################################################
param_squid ()
{
# paramètrage de Squid (connecté en série derrière Dansguardian)
        [ -e /etc/squid/squid.conf.default  ] || cp /etc/squid/squid.conf /etc/squid/squid.conf.default
# suppression des références 'localnet', 'icp', 'htcp' et 'always_direct'
        $SED "/^acl localnet/d" /etc/squid/squid.conf
        $SED "/^icp_access allow localnet/d" /etc/squid/squid.conf
        $SED "/^icp_port 3130/d" /etc/squid/squid.conf
        $SED "/^http_access allow localnet/d" /etc/squid/squid.conf
        $SED "/^htcp_access allow localnet/d" /etc/squid/squid.conf
        $SED "/^always_direct allow localnet/d" /etc/squid/squid.conf
# mode 'proxy transparent local'
        $SED "s?^http_port.*?http_port 127.0.0.1:3128 transparent?g" /etc/squid/squid.conf
# Configuration du cache local
        $SED "s?^#cache_dir.*?cache_dir ufs \/var\/spool\/squid 256 16 256?g" /etc/squid/squid.conf
# emplacement et formatage standard des logs
        echo '#logformat common %>a %ui %un [%tl] "%rm %ru HTTP/%rv" %>Hs %<st %Ss:%Sh' >> /etc/squid/squid.conf
        echo '#logformat combined %>a %ui %un [%tl] "%rm %ru HTTP/%rv" %>Hs %<st "%{Referer}>h" "%{User-Agent}>h" %Ss:%Sh' >> /etc/squid/squid.conf
        echo "access_log /var/log/squid/access.log" >> /etc/squid/squid.conf
# compatibilité des logs avec awstats
        echo "emulate_httpd_log on" >> /etc/squid/squid.conf
        echo "half_closed_clients off" >> /etc/squid/squid.conf
        echo "server_persistent_connections off" >> /etc/squid/squid.conf
        echo "client_persistent_connections on" >> /etc/squid/squid.conf
        echo "client_lifetime 1440 minutes" >> /etc/squid/squid.conf
        echo "request_timeout 5 minutes" >> /etc/squid/squid.conf
        echo "persistent_request_timeout 2 minutes" >> /etc/squid/squid.conf
        echo "cache_mem 256 MB" >> /etc/squid/squid.conf
        echo "maximum_object_size_in_memory 4096 KB" >> /etc/squid/squid.conf
        echo "maximum_object_size     4096 KB" >> /etc/squid/squid.conf
# anonymisation of squid version
        echo "via off" >> /etc/squid/squid.conf
# remove the 'X_forwarded' http option
        echo "forwarded_for delete" >> /etc/squid/squid.conf
# linked squid output in HAVP input
        echo "cache_peer 127.0.0.1 parent 8090 0 no-query default" >> /etc/squid/squid.conf
        echo "never_direct allow all" >> /etc/squid/squid.conf
# avoid error messages on network interfaces state changes
        $SED "s?^SQUID_AUTO_RELOAD.*?SQUID_AUTO_RELOAD=no?g" /etc/sysconfig/squid
# reduce squid shutdown time (100 to 50)
        $SED "s?^SQUID_SHUTDOWN_TIMEOUT.*?SQUID_SHUTDOWN_TIMEOUT=50?g" /etc/sysconfig/squid

# Squid cache init
        /usr/sbin/squid -z
}  # End of param_squid ()
        
##################################################################
##              Fonction param_dansguardian                     ##
## - Paramètrage du gestionnaire de contenu Dansguardian       ##
##################################################################
param_dansguardian ()
{
        mkdir /var/dansguardian
        chown dansguardian /var/dansguardian
        [ -e $DIR_DG/dansguardian.conf.default ] || cp $DIR_DG/dansguardian.conf $DIR_DG/dansguardian.conf.default
# Le filtrage est désactivé par défaut 
        $SED "s/^reportinglevel =.*/reportinglevel = -1/g" $DIR_DG/dansguardian.conf
# la page d'interception est en français
        $SED "s?^language =.*?language = french?g" $DIR_DG/dansguardian.conf
# on limite l'écoute de Dansguardian côté LAN
        $SED "s?^filterip.*?filterip = $PRIVATE_IP?g" $DIR_DG/dansguardian.conf
# on chaîne Dansguardian au proxy cache SQUID
        $SED "s?^proxyport.*?proxyport = 3128?g" $DIR_DG/dansguardian.conf
# on remplace la page d'interception (template)
        cp -f $DIR_CONF/template.html /usr/share/dansguardian/languages/ukenglish/
        cp -f $DIR_CONF/template-fr.html /usr/share/dansguardian/languages/french/template.html
# on ne loggue que les deny (pour le reste, on a squid)
        $SED "s?^loglevel =.*?loglevel = 1?g" $DIR_DG/dansguardian.conf
# lauch of 10 daemons (20 in largest server)
        $SED "s?^minchildren =.*?minchildren = 10?g" $DIR_DG/dansguardian.conf
# on désactive par défaut le controle de contenu des pages html
        $SED "s?^weightedphrasemode =.*?weightedphrasemode = 0?g" $DIR_DG/dansguardian.conf
        cp $DIR_DG/lists/bannedphraselist $DIR_DG/lists/bannedphraselist.default
        $SED "s?^[^#]?#&?g" $DIR_DG/lists/bannedphraselist # (on commente ce qui ne l'est pas)
# on désactive par défaut le contrôle d'URL par expressions régulières
        cp $DIR_DG/lists/bannedregexpurllist $DIR_DG/lists/bannedregexpurllist.default
        $SED "s?^[^#]?#&?g" $DIR_DG/lists/bannedregexpurllist # (on commente ce qui ne l'est pas)
# on désactive par défaut le contrôle de téléchargement de fichiers
        [ -e $DIR_DG/dansguardianf1.conf.default ] || cp $DIR_DG/dansguardianf1.conf $DIR_DG/dansguardianf1.conf.default
        $SED "s?^blockdownloads =.*?blockdownloads = off?g" $DIR_DG/dansguardianf1.conf
        [ -e $DIR_DG/lists/bannedextensionlist.default ] || mv $DIR_DG/lists/bannedextensionlist $DIR_DG/lists/bannedextensionlist.default
        [ -e $DIR_DG/lists/bannedmimetypelist.default ] || mv $DIR_DG/lists/bannedmimetypelist $DIR_DG/lists/bannedmimetypelist.default
        touch $DIR_DG/lists/bannedextensionlist
        touch $DIR_DG/lists/bannedmimetypelist
# 'Safesearch' regex actualisation
        $SED "s?images?search?g" $DIR_DG/lists/urlregexplist
# 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
# Keep a copy of URL & domain filter configuration files
        [ -e $DIR_DG/lists/bannedsitelist.default ] || mv $DIR_DG/lists/bannedsitelist $DIR_DG/lists/bannedsitelist.default
        [ -e $DIR_DG/lists/bannedurllist.default ] || mv $DIR_DG/lists/bannedurllist $DIR_DG/lists/bannedurllist.default
} # End of param_dansguardian ()

##################################################################
##                      Fonction antivirus                      ##
## - configuration havp + libclamav                             ##
##################################################################
antivirus ()            
{
# création de l'usager 'havp'
        havp_exist=`grep havp /etc/passwd|wc -l`
        if [ "$havp_exist" == "1" ]
        then
              userdel -r havp 2>/dev/null
              groupdel havp 2>/dev/null
        fi
        groupadd -f havp
        useradd -r -g havp -s /bin/false -c "system user for havp" havp
        mkdir -p /var/tmp/havp /var/log/havp
        chown -R havp /var/tmp/havp /var/log/havp /var/run/havp
        $SED "/$HAVP_BIN -c $HAVP_CONFIG/i chown -R havp:havp \/var\/tmp\/havp" /etc/init.d/havp
# configuration d'HAVP
        [ -e /etc/havp/havp.config.default ] || cp /etc/havp/havp.config /etc/havp/havp.config.default
        $SED "/^REMOVETHISLINE/d" /etc/havp/havp.config
        $SED "s?^# PORT.*?PORT 8090?g" /etc/havp/havp.config                            # datas come on 8090                    
        $SED "s?^# BIND_ADDRESS.*?BIND_ADDRESS 127.0.0.1?g" /etc/havp/havp.config       # we listen only on loopback
        $SED "s?^ENABLECLAMLIB.*?ENABLECLAMLIB true?g" /etc/havp/havp.config            # active libclamav AV
        $SED "s?^# LOG_OKS.*?LOG_OKS false?g" /etc/havp/havp.config                     # log only when malware matches
        $SED "s?^# SERVERNUMBER.*?SERVERNUMBER 10?g" /etc/havp/havp.config              # 10 daemons are started simultaneously
        $SED "s?^# SCANIMAGES.*?SCANIMAGES false?g" /etc/havp/havp.config               # doesn't scan image files
        $SED "s?^# SKIPMIME.*?SKIPMIME image\/\* video\/\* audio\/\*?g" /etc/havp/havp.config # doesn't scan some multimedia files
# remplacement du fichier d'initialisation
        [ -e /etc/init.d/havp.default ] || cp /etc/init.d/havp /etc/init.d/havp.default
        cp -f $DIR_CONF/havp-init /etc/init.d/havp
# on remplace la page d'interception (template)
        cp -f $DIR_CONF/virus-fr.html /etc/havp/templates/fr/virus.html
        cp -f $DIR_CONF/virus-en.html /etc/havp/templates/en/virus.html
# automatisation de la mise à jour de la base antivirale (toutes les 2 heures)
        $SED "s?^Checks.*?Checks 12?g" /etc/freshclam.conf
        $SED "s?^NotifyClamd.*?# NotifyClamd /etc/clamd.conf?g" /etc/freshclam.conf
# Virus database update
        rm -f /var/lib/clamav/*.cld # in case of old database scheme
        [ -e /var/lib/clamav/main.cvd ] || /usr/bin/freshclam
}

##################################################################################
##                      param_ulogd function                                    ##
## - Ulog config for multi-log files                                            ##
##################################################################################
param_ulogd ()
{
# Three instances of ulogd (three different logfiles)
        [ -d /var/log/firewall ] || mkdir -p /var/log/firewall
        nl=1
        for log_type in tracability ssh ext-access
        do
                [ -e /var/log/firewall/$log_type.log ] || touch /var/log/firewall/$log_type.log
                cp -f /etc/ulogd.conf /etc/ulogd-$log_type.conf
                $SED "s?^nlgroup=.*?nlgroup=$nl?g" /etc/ulogd-$log_type.conf 
                $SED '/OPRINT/,$d' /etc/ulogd-$log_type.conf
                cat << EOF >> /etc/ulogd-$log_type.conf
[LOGEMU]
file="/var/log/firewall/$log_type.log"
sync=1
EOF
                nl=`expr $nl + 1`
        done
        chown -R root:apache /var/log/firewall
        chmod 750 /var/log/firewall
        chmod 640 /var/log/firewall/*
        [ -e /etc/init.d/ulogd.default ] || cp /etc/init.d/ulogd /etc/init.d/ulogd.default
        cp -f $DIR_CONF/ulogd-init /etc/init.d/ulogd
}  # End of param_ulogd ()

##################################################################################
##                              Fonction param_awstats                          ##
## - configuration de l'interface des logs de consultation WEB (AWSTAT)         ##
##################################################################################
param_awstats()
{
        cp -rf /usr/share/awstats/www/ $DIR_ACC/awstats/
        chown -R apache:apache $DIR_ACC/awstats
        cp /etc/awstats/awstats.conf /etc/awstats/awstats.conf.default
        $SED "s?^LogFile=.*?LogFile=\"/var/log/squid/access.log\"?g" /etc/awstats/awstats.conf
        $SED "s?^LogFormat=.*?LogFormat=4?g" /etc/awstats/awstats.conf
        $SED "s?^SiteDomain=.*?SiteDomain=\"$HOSTNAME\"?g" /etc/awstats/awstats.conf
        $SED "s?^HostAliases=.*?HostAliases=\"$PRIVATE_IP\"?g" /etc/awstats/awstats.conf
        $SED "s?^DNSLookup=.*?DNSLookup=0?g" /etc/awstats/awstats.conf
        $SED "s?^DirData=.*?DirData=\"/var/lib/awstats\"?g" /etc/awstats/awstats.conf
        $SED "s?^DirIcons=.*?DirIcons=\"/acc/awstats/icon\"?g" /etc/awstats/awstats.conf
        $SED "s?^StyleSheet=.*?StyleSheet=\"/css/style.css\"?g" /etc/awstats/awstats.conf
        $SED "s?^BuildReportFormat=.*?BuildReportFormat=xhtml?g" /etc/awstats/awstats.conf
        $SED "s?^UseFramesWhenCGI=.*?UseFramesWhenCGI=0?g" /etc/awstats/awstats.conf
        $SED "s?^UseFramesWhenCGI=.*?UseFramesWhenCGI=0?g" /etc/awstats/awstats.conf
        $SED "s?^ShowSummary=.*?ShowSummary=VPHB?g" /etc/awstats/awstats.conf
        $SED "s?^ShowSummary=.*?ShowSummary=VPHB?g" /etc/awstats/awstats.conf
        $SED "s?^ShowMonthStats=.*?ShowMonthStats=VPHB?g" /etc/awstats/awstats.conf
        $SED "s?^ShowDaysOfMonthStats=.*?ShowDaysOfMonthStats=PHB?g" /etc/awstats/awstats.conf
        $SED "s?^ShowDaysOfWeekStats=.*?ShowDaysOfWeekStats=PHB?g" /etc/awstats/awstats.conf
        $SED "s?^ShowHoursStats=.*?ShowHoursStats=PHB?g" /etc/awstats/awstats.conf
        $SED "s?^ShowDomainsStats=.*?ShowDomainsStats=0?g" /etc/awstats/awstats.conf
        $SED "s?^ShowHostsStats=.*?ShowHostsStats=0?g" /etc/awstats/awstats.conf
        $SED "s?^ShowAuthenticatedUsers=.*?ShowAuthenticatedUsers=0?g" /etc/awstats/awstats.conf
        $SED "s?^ShowRobotsStats=.*?ShowRobotsStats=0?g" /etc/awstats/awstats.conf
        $SED "s?^ShowFileTypesStats=.*?ShowFileTypesStats=0?g" /etc/awstats/awstats.conf
        $SED "s?^ShowFileSizesStats=.*?ShowFileSizesStats=0?g" /etc/awstats/awstats.conf
        $SED "s?^ShowOSStats=.*?ShowOSStats=0?g" /etc/awstats/awstats.conf
        $SED "s?^ShowScreenSizeStats=.*?ShowScreenSizeStats=0?g" /etc/awstats/awstats.conf

        cat <<EOF >> /etc/httpd/conf/webapps.d/alcasar.conf
<Directory $DIR_ACC/awstats>
        SSLRequireSSL
        Options ExecCGI
        AddHandler cgi-script .pl
        DirectoryIndex awstats.pl
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        Allow from $PRIVATE_NETWORK_MASK
        require valid-user
        AuthType digest
        AuthName $HOSTNAME
        BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On
        AuthUserFile $DIR_DEST_ETC/digest/key_admin
        ErrorDocument 404 https://$HOSTNAME/
</Directory>
SetEnv PERL5LIB /usr/share/awstats/lib:/usr/share/awstats/plugins
EOF
} # End of param_awstats ()

##########################################################
##              Fonction param_dnsmasq                  ##
##########################################################
param_dnsmasq ()
{
        [ -d /var/log/dnsmasq ] || mkdir /var/log/dnsmasq
        $SED "s?^DHCP_LEASE=.*?DHCP_LEASE=/var/log/dnsmasq/lease.log?g" /etc/sysconfig/dnsmasq # fichier contenant les baux
        [ -e /etc/dnsmasq.conf.default ] || cp /etc/dnsmasq.conf /etc/dnsmasq.conf.default
# 1st dnsmasq listen on udp 53 ("dnsmasq - forward"). It's used as dhcp server only if bypass is on.
        cat << EOF > /etc/dnsmasq.conf 
# Configuration file for "dnsmasq in forward mode"
conf-file=$DIR_DEST_ETC/alcasar-dns-name        # zone de definition de noms DNS locaux
listen-address=$PRIVATE_IP
listen-address=127.0.0.1
no-dhcp-interface=$INTIF
bind-interfaces
cache-size=256
domain=$DOMAIN
domain-needed
expand-hosts
bogus-priv
filterwin2k
server=$DNS1
server=$DNS2
# le servive DHCP est configuré mais n'est exploité que pour le "bypass"
dhcp-range=$PRIVATE_FIRST_IP,$PRIVATE_LAST_IP,$PRIVATE_NETMASK,12h
dhcp-option=option:router,$PRIVATE_IP
#dhcp-option=option:ntp-server,192.168.0.4,10.10.0.5

# Exemple de configuration statique : <@MAC>,<name>,<@IP>,<MASK>,<ttl bail>
#dhcp-host=11:22:33:44:55:66,ssic-test,192.168.182.20,255.255.255.0,45m
EOF
# 2nd dnsmasq listen on udp 54 ("dnsmasq with blackhole")
        cat << EOF > /etc/dnsmasq-blackhole.conf 
        # Configuration file for "dnsmasq with blackhole"
# Inclusion de la blacklist <domains> de Toulouse dans la configuration
conf-dir=$DIR_DEST_ETC/alcasar-dnsfilter-enabled
conf-file=$DIR_DEST_ETC/alcasar-dns-name        # zone de definition de noms DNS locaux
listen-address=$PRIVATE_IP
port=54
no-dhcp-interface=$INTIF
bind-interfaces
cache-size=256
domain=$DOMAIN
domain-needed
expand-hosts
bogus-priv
filterwin2k
server=$DNS1
server=$DNS2
EOF

# Init file modification
[ -e /etc/init.d/dnsmasq.default ] || cp /etc/init.d/dnsmasq /etc/init.d/dnsmasq.default
# Start and stop a 2nd process for the "DNS blackhole"
$SED "/daemon/a \$dnsmasq -C /etc/dnsmasq-blackhole.conf \$OPTIONS" /etc/init.d/dnsmasq
$SED "/killproc \$DAEMON_NAME/a killproc \$DAEMON_NAME" /etc/init.d/dnsmasq
# Start after chilli (65) which create tun0
$SED "s?^# chkconfig:.*?# chkconfig: 2345 99 40?g" /etc/init.d/dnsmasq
# Optionnellement on pré-active les logs DNS des clients
[ -e /etc/sysconfig/dnsmasq.default ] || cp /etc/sysconfig/dnsmasq /etc/sysconfig/dnsmasq.default
$SED "s?log-facility?#OPTIONS=\"-q --log-facility=/var/log/dnsmasq/queries.log\"?g"  /etc/sysconfig/dnsmasq
# Optionnellement, exemple de configuration avec un A.D.
echo '#OPTIONS="$OPTIONS --server=/your.domain/192.168.182.2"' >> /etc/sysconfig/dnsmasq
} # End dnsmasq

##########################################################
##              Fonction BL (BlackList)                 ##
##########################################################
BL ()
{
# on copie par défaut la BL de toulouse embarqués dans l'archive d'ALCASAR
        rm -rf $DIR_DG/lists/blacklists
        tar zxf $DIR_CONF/blacklists.tar.gz --directory=$DIR_DG/lists/ > /dev/null 2>&1
# on crée le répertoire ossi (noms de domaine et URLs ajoutés à la BL)
        mkdir $DIR_DG/lists/blacklists/ossi
        touch $DIR_DG/lists/blacklists/ossi/domains
        touch $DIR_DG/lists/blacklists/ossi/urls
# On crée les fichiers vides de sites ou d'URL réhabilités
        [ -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
# On crée la configuration de base du filtrage de domaine et d'URL pour Dansguardian
        cat <<EOF > $DIR_DG/lists/bannedurllist
# Dansguardian filter config for ALCASAR
EOF
        cat <<EOF > $DIR_DG/lists/bannedsitelist
# Dansguardian domain filter config for ALCASAR
# block all sites except those in the exceptionsitelist --> liste blanche (désactivée)
#**
# 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
# On ajoute Bing et Youtube à la récriture d'URL liée au contrôle scolaire/parental
        cat <<EOF >> $DIR_DG/lists/urlregexplist
# Bing - add 'adlt=strict'
#"(^http://[0-9a-z]+\.bing\.[a-z]+[-/%.0-9a-z]*\?)(.*)"->"\1\2&adlt=strict"
# Youtube - add 'edufilter=your_ID' 
#"(^http://[0-9a-z]+\.youtube\.[a-z]+[-/%.0-9a-z]*\?)(.*)"->"\1\2&edufilter=ABCD1234567890abcdef"
EOF
        chown -R dansguardian:apache $DIR_DG
        chmod -R g+rw $DIR_DG
# On crée la structure du DNS-blackhole :
        mkdir $DIR_DEST_ETC/{alcasar-dnsfilter-available,alcasar-dnsfilter-enabled}
        chown -R 770 $DIR_DEST_ETC/{alcasar-dnsfilter-available,alcasar-dnsfilter-enabled}
        chown -R root:apache $DIR_DEST_ETC/{alcasar-dnsfilter-available,alcasar-dnsfilter-enabled}
# On adapte la BL de Toulouse à notre structure
        if [ "$mode" != "update" ]; then
                $DIR_DEST_SBIN/alcasar-bl.sh --adapt
        fi
}

##########################################################
##              Fonction cron                           ##
## - Mise en place des différents fichiers de cron     ##
##########################################################
cron ()
{
# Modif du fichier 'crontab' pour passer les cron à minuit au lieu de 04h00
        [ -e /etc/crontab.default ] || cp /etc/crontab /etc/crontab.default
        cat <<EOF > /etc/crontab
SHELL=/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-export_log
7       15      cron.logClean           nice /etc/cron.d/alcasar-clean_log
7       20      cron.importClean        nice /etc/cron.d/alcasar-clean_import
EOF
        cat <<EOF > /etc/cron.d/alcasar-clean_log
# suppression des fichiers de logs de plus d'un an (tous les lundi à 4h30)
30 4 * * 1 root $DIR_DEST_BIN/alcasar-log.sh --clean
EOF
        cat <<EOF > /etc/cron.d/alcasar-mysql
# Contrôle, réparation et export de la base des usagers (tous les lundi à 4h45)
45 4 * * 1 root $DIR_DEST_SBIN/alcasar-mysql.sh --dump
# Nettoyage des utilisateurs dont la date d'expiration du compte est supérieure à 7 jours
40 4 * * * root /usr/local/sbin/alcasar-mysql.sh --expire_user 2>&1 >/dev/null
EOF
        cat <<EOF > /etc/cron.d/alcasar-export_log
# export des log squid, firewall et apache (tous les lundi à 5h00)
00 5 * * 1 root $DIR_DEST_BIN/alcasar-log.sh --export
EOF
        cat <<EOF > /etc/cron.d/alcasar-archive
# Archive des logs et de la base de données (tous les lundi à 5h35)
35 5 * * 1 root $DIR_DEST_BIN/alcasar-archive.sh --now
EOF
        cat << EOF > /etc/cron.d/awstats
# mise à jour des stats de consultation WEB toutes les 30'
*/30 * * * * root $DIR_ACC/awstats/awstats.pl -config=localhost -update >/dev/null 2>&1
EOF
        cat << EOF > /etc/cron.d/alcasar-clean_import
# suppression des fichiers de mots de passe lors d'imports massifs par fichier de plus de 24h
30 * * * *  root $DIR_DEST_BIN/alcasar-import-clean.sh
EOF
        cat << EOF > /etc/cron.d/alcasar-distrib-updates
# mise à jour automatique de la distribution tous les jours 3h30
30 3 * * *  root /usr/sbin/urpmi --auto-update --auto 2>&1
EOF
# mise à jour des stats de connexion (accounting). Scripts provenant de "dialupadmin" (rpm freeradius-web) (cf. wiki.freeradius.org/Dialup_admin).
# on écrase le crontab d'origine installé par le RPM "freeradius-web" (bug remonté à qa.mandriva.com : 46739).
# 'tot_stats' (tout les jours à 01h01) : aggrégat des connexions journalières par usager (renseigne la table 'totacct') 
# 'monthly_tot_stat' (tous les jours à 01h05) : aggrégat des connexions mensuelles par usager (renseigne la table 'mtotacct')
# 'truncate_raddact' (tous les 1er du mois à 01h10) : supprime les entrées journalisées plus vieilles que '$back_days' jours (défini ci-après)
# 'clean_radacct' (tous les 1er du mois à 01h15) : ferme les session ouvertes de plus de '$back_days' jours (défini ci-après)
        $SED "s?^\$back_days.*?\$back_days = 365;?g" /usr/bin/truncate_radacct
        $SED "s?^\$back_days.*?\$back_days = 30;?g" /usr/bin/clean_radacct
        rm -f /etc/cron.daily/freeradius-web
        rm -f /etc/cron.monthly/freeradius-web
        cat << EOF > /etc/cron.d/freeradius-web
1 1 * * * root /usr/bin/tot_stats > /dev/null 2>&1
5 1 * * * root /usr/bin/monthly_tot_stats > /dev/null 2>&1
10 1 1 * * root /usr/bin/truncate_radacct > /dev/null 2>&1
15 1 1 * * root /usr/bin/clean_radacct > /dev/null 2>&1
EOF
        cat << EOF > /etc/cron.d/alcasar-watchdog
# activation du "chien de garde" (watchdog) toutes les 3'
*/3 * * * * root $DIR_DEST_BIN/alcasar-watchdog.sh > /dev/null 2>&1
EOF
# activation du "chien de garde des services" (watchdog) toutes les 18'
        cat << EOF > /etc/cron.d/alcasar-daemon-watchdog
# activation du "chien de garde" (daemon-watchdog) toutes les 18'
*/18 * * * * root $DIR_DEST_BIN/alcasar-daemon.sh > /dev/null 2>&1
EOF
# suppression des crons usagers
        rm -f /var/spool/cron/*
} # End cron

##################################################################
##                      Fonction post_install                   ##
## - Modification des bannières (locales et ssh) et des prompts ##
## - Installation de la structure de chiffrement pour root      ##
## - Mise en place du sudoers et de la sécurité sur les fichiers##
## - Mise en place du la rotation des logs                      ##
## - Configuration dans le cas d'une mise à jour               ##
##################################################################
post_install()
{
# adaptation du script "chien de garde" (watchdog)
        $SED "s?^EXTIF=.*?EXTIF=\"$EXTIF\"?g" $DIR_DEST_BIN/alcasar-watchdog.sh
        $SED "s?^INTIF=.*?INTIF=\"$INTIF\"?g" $DIR_DEST_BIN/alcasar-watchdog.sh
# création de la bannière locale
        [ -e /etc/mandriva-release.default ]  || cp /etc/mandriva-release /etc/mandriva-release.default
        cp -f $DIR_CONF/banner /etc/mandriva-release
        echo " V$VERSION" >> /etc/mandriva-release
# création de la bannière SSH
        cp /etc/mandriva-release /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
# postfix banner anonymisation
        $SED "s?^smtpd_banner =.*?smtpd_banner = $myhostname ESMTP?g" /etc/postfix/main.cf
# sshd écoute côté LAN et WAN
        $SED "s?^#ListenAddress 0\.0\.0\.0?ListenAddress $PRIVATE_IP?g" /etc/ssh/sshd_config
        $SED "/^ListenAddress $PRIVATE_IP/a\ListenAddress $PUBLIC_IP" /etc/ssh/sshd_config 
        # Put the default value in conf file (sshd, QOS and protocols/dns/ are off)(web antivirus is on)
        /sbin/chkconfig --del sshd
        echo "SSH=off" >> $CONF_FILE
        echo 'Admin_from_IP="0.0.0.0/0.0.0.0"' >> $CONF_FILE
        echo "QOS=off" >> $CONF_FILE
        echo "LDAP=off" >> $CONF_FILE
        echo "LDAP_IP=0.0.0.0/0.0.0.0" >> $CONF_FILE
        echo "WEB_ANTIVIRUS=on" >> $CONF_FILE
        echo "PROTOCOLS_FILTERING=off" >> $CONF_FILE
        echo "DNS_FILTERING=off" >> $CONF_FILE
        echo "YOUTUBE_ID=ABCD1234567890abcdef" >> $CONF_FILE
# Coloration des prompts
        [ -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
# Droits d'exécution pour utilisateur apache et 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
# prise en compte de la rotation des logs sur 1 an (concerne mysql, httpd, dansguardian, squid, radiusd, ulogd)
        cp -f $DIR_CONF/logrotate.d/* /etc/logrotate.d/
        chmod 644 /etc/logrotate.d/*
# rectification sur versions précédentes de la compression des logs
        $SED "s?^delaycompress.*?#&?g" /etc/logrotate.conf
# actualisation des fichiers logs compressés
        for dir in firewall squid dansguardian httpd
        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
# export des logs en 'retard' dans /var/Save/logs
        /usr/local/bin/alcasar-log.sh --export
# processus lancés par défaut au démarrage
        for i in ntpd iptables ulogd dnsmasq squid chilli httpd radiusd netfs mysqld dansguardian havp freshclam
        do
                /sbin/chkconfig --add $i
        done
# On rajoute une tempo pour relancer radius après le redémarrage de mysqld (bug en cours d'analyse)
        cat << EOF > /etc/rc.local
#!/bin/sh
#
### BEGIN INIT INFO
# Provides: rc.local
# X-Mandriva-Compat-Mode
# Default-Start: 2 3 4 5
# Short-Description: Local initialization script
# Description: This script will be executed *after* all the other init scripts.
#              You can put your own initialization stuff in here if you don't
#              want to do the full Sys V style init stuff.
### END INIT INFO

/etc/init.d/mysqld restart
sleep 1
/etc/init.d/radiusd restart

touch /var/lock/subsys/local
EOF
# pour éviter les alertes de dépendance entre service.
        $SED "s?^# Required-Start.*?# Required-Start: \$local_fs \$network?g" /etc/init.d/mysqld
        $SED "s?^# Required-Stop.*?# Required-Stop: \$local_fs \$network?g" /etc/init.d/mysqld
        $SED "s?^# Should-Start.*?# Should-Start: radiusd ldap?g" /etc/init.d/httpd
        $SED "s?^# Should-Stop.*?# Should-Stop: radiusd ldap?g" /etc/init.d/httpd
# On affecte le niveau de sécurité du système : type "fileserver"
        $SED "s?BASE_LEVEL=.*?BASE_LEVEL=fileserver?g" /etc/security/msec/security.conf
# On supprime la vérification du mode promiscious des interfaces réseaux ( nombreuses alertes sur eth1 dûes à Tun0 )
        $SED "s?CHECK_PROMISC=.*?CHECK_PROMISC=no?g" /etc/security/msec/level.fileserver
# On applique les préconisations ANSSI (sysctl + msec quand c'est possible)
# Apply French Security Agency rules (sysctl + msec when possible)
# ignorer les broadcast ICMP. (attaque smurf) 
$SED "s?^ACCEPT_BROADCASTED_ICMP_ECHO=.*?ACCEPT_BROADCASTED_ICMP_ECHO=no?g" /etc/security/msec/level.fileserver
sysctl -w net.ipv4.icmp_echo_ignore_broadcasts=1
# ignorer les erreurs ICMP bogus
$SED "s?^ACCEPT_BOGUS_ERROR_RESPONSES=.*?ACCEPT_BOGUS_ERROR_RESPONSES=no?g" /etc/security/msec/level.fileserver
sysctl -w net.ipv4.icmp_ignore_bogus_error_responses=1
# désactiver l'envoi et la réponse aux ICMP redirects
sysctl -w net.ipv4.conf.all.accept_redirects=0
accept_redirect=`grep accept_redirect /etc/sysctl.conf|wc -l`
        if [ "$accept_redirect" == "0" ]
        then
                echo "net.ipv4.conf.all.accept_redirects = 0" >> /etc/sysctl.conf
        else
                $SED "s?accept_redirects.*?accept_redirects = 0?g" /etc/sysctl.conf
        fi
sysctl -w net.ipv4.conf.all.send_redirects=0
send_redirect=`grep send_redirect /etc/sysctl.conf|wc -l`
        if [ "$send_redirect" == "0" ]
        then
                echo "net.ipv4.conf.all.send_redirects = 0" >> /etc/sysctl.conf
        else
                $SED "s?send_redirects.*?send_redirects = 0?g" /etc/sysctl.conf
        fi
# activer les SYN Cookies (attaque syn flood)
sysctl -w net.ipv4.tcp_syncookies=1
tcp_syncookies=`grep tcp_syncookies /etc/sysctl.conf|wc -l`
        if [ "$tcp_syncookies" == "0" ]
        then
                echo "net.ipv4.tcp_syncookies = 1" >> /etc/sysctl.conf
        else
                $SED "s?tcp_syncookies.*?tcp_syncookies = 1?g" /etc/sysctl.conf
        fi
# activer l'antispoofing niveau Noyau
$SED "s?^ENABLE_IP_SPOOFING_PROTECTION.*?ENABLE_IP_SPOOFING_PROTECTION=yes?g" /etc/security/msec/level.fileserver
sysctl -w net.ipv4.conf.all.rp_filter=1
# ignorer le source routing
sysctl -w net.ipv4.conf.all.accept_source_route=0
accept_source_route=`grep accept_source_route /etc/sysctl.conf|wc -l`
        if [ "$accept_source_route" == "0" ]
        then
                echo "net.ipv4.conf.all.accept_source_route = 0" >> /etc/sysctl.conf
        else
                $SED "s?accept_source_route.*?accept_source_route = 0?g" /etc/sysctl.conf
        fi
# réglage du timer de maintien de suivi de session à 1h (3600s) au lieu de 5 semaines
sysctl -w net.netfilter.nf_conntrack_tcp_timeout_established=3600
timeout_established=`grep timeout_established /etc/sysctl.conf|wc -l`
        if [ "$timeout_established" == "0" ]
        then
                echo "net.netfilter.nf_conntrack_tcp_timeout_established = 3600" >> /etc/sysctl.conf
        else
                $SED "s?timeout_established.*?timeout_established = 3600?g" /etc/sysctl.conf
        fi
# suppression des log_martians (ALCASAR est souvent entre deux réseaux en adressage privée) 
sysctl -w net.ipv4.conf.all.log_martians=0
$SED "s?^ENABLE_LOG_STRANGE_PACKETS=.*?ENABLE_LOG_STRANGE_PACKETS=no?g" /etc/security/msec/level.fileserver


# On supprime la gestion du <CTRL>+<ALT>+<SUPPR> et des Magic SysReq Keys
        $SED "s?^ALLOW_REBOOT=.*?ALLOW_REBOOT=no?g" /etc/security/msec/level.fileserver
# On mets en place la sécurité sur les fichiers
# des modif par rapport à radius update
        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/freeradius-web/config.php          root.apache     640
/etc/raddb/dictionnary                  root.radius     640
/etc/raddb/ldap.attrmap                 root.radius     640
/etc/raddb/hints                        root.radius     640
/etc/raddb/huntgroups                   root.radius     640
/etc/raddb/attrs.access_reject          root.radius     640
/etc/raddb/attrs.accounting_response    root.radius     640
/etc/raddb/acct_users                   root.radius     640
/etc/raddb/preproxy_users               root.radius     640
/etc/raddb/modules/ldap                 radius.apache   660
/etc/raddb/sites-available/alcasar      radius.apache   660
/etc/pki/*                              root.apache     750
EOF
        /usr/sbin/msec
# modification /etc/inittab
        [ -e /etc/inittab.default ] || cp /etc/inittab /etc/inittab.default
# On ne garde que 3 terminaux
        $SED "s?^4.*?#&?g" /etc/inittab
        $SED "s?^5.*?#&?g" /etc/inittab
        $SED "s?^6.*?#&?g" /etc/inittab
# On limite le temps d'attente de grub (3s) et on change la résolution d'écran
$SED "s?^timeout.*?timeout 3?g" /boot/grub/menu.lst
$SED "s?^kernel.*?& vga=791?g" /boot/grub/menu.lst
$SED "s? vga=791??2g" /boot/grub/menu.lst
# On supprime les services et les utilisateurs inutiles
for svc in alsa sound dm atd bootlogd stop-bootlogd
do
        /sbin/chkconfig --del $svc
done
for rm_users in avahi-autoipd avahi icapd
do
        user=`cat /etc/passwd|grep $rm_users|cut -d":" -f1`
        if [ "$user" == "$rm_users" ]
        then
                /usr/sbin/userdel -f $rm_users
        fi
done
# Load and update the previous conf file
if [ "$mode" = "update" ]
then
        $DIR_DEST_BIN/alcasar-conf.sh --load
        $SED "s?^INSTALL_DATE=.*?INSTALL_DATE=$DATE?g" $CONF_FILE
        $SED "s?^VERSION=.*?VERSION=$VERSION?g" $CONF_FILE
fi
rm -f /tmp/alcasar-conf*
chown -R root:apache $DIR_DEST_ETC/*
chmod -R 660 $DIR_DEST_ETC/*
chmod ug+x $DIR_DEST_ETC/digest $DIR_DEST_ETC/alcasar-dnsfilter*
        cd $DIR_INSTALL
        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://alcasar"
                echo
                echo "                   Appuyez sur 'Entrée' pour continuer"
        else    
                echo "#                        Enf 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://alcasar"
                echo
                echo "                   Hit 'Enter' to continue"
        fi
        sleep 2
        if [ "$mode" != "update" ]
        then
                read a
        fi
        clear
# Apply and save the firewall rules
        sh $DIR_DEST_BIN/alcasar-iptables.sh
        sleep 2
        reboot
} # End post_install ()

#################################
#  Boucle principale du script  #
#################################
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
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
case $args in
        -\? | -h* | --h*)
                echo "$usage"
                exit 0
                ;;
        -i | --install)
                license
                header_install
                testing
# Test if ALCASAR is already installed
                if [ -e $DIR_WEB/VERSION ]
                then
                        actual_version=`cat $DIR_WEB/VERSION`
                        if [ $Lang == "fr" ]
                                then echo -n "La version "; echo -n $actual_version ; echo " d'ALCASAR est déjà installée";
                                else echo -n "ALCASAR Version "; echo -n $actual_version ; echo " is already installed";
                        fi
                        response=0
                        PTN='^[oOnNyY]$'
                        until [[ $(expr $response : $PTN) -gt 0 ]]
                        do
                                if [ $Lang == "fr" ]
                                        then echo -n "Voulez-vous effectuer une mise à jour (O/n)? ";
                                        else echo -n "Do you want to update (Y/n)?";
                                 fi
                                read response
                        done
                        if [ "$response" = "n" ] || [ "$response" = "N" ] 
                        then
                                rm -f /tmp/alcasar-conf*
                        else
                                RUNNING_VERSION=`cat $DIR_WEB/VERSION|cut -d" " -f1`
                                MAJ_RUNNING_VERSION=`echo $RUNNING_VERSION|cut -d"." -f1`
                                MIN_RUNNING_VERSION=`echo $RUNNING_VERSION|cut -d"." -f2|cut -c1`
                                UPD_RUNNING_VERSION=`echo $RUNNING_VERSION|cut -d"." -f3`
# Create a backup of running version importants files
                                chmod u+x $DIR_SCRIPTS/alcasar-conf.sh
                                $DIR_SCRIPTS/alcasar-conf.sh --create
                                mode="update"
                        fi
                fi
# RPMs install
                $DIR_SCRIPTS/alcasar-urpmi.sh
                if [ "$?" != "0" ]
                then
                        exit 0
                fi
                if [ -e $DIR_WEB/VERSION ]
                then
# Uninstall the running version
                        $DIR_SCRIPTS/sbin/alcasar-uninstall.sh
                fi
# Test if manual update 
                if [ -e /tmp/alcasar-conf.tar.gz ] && [ "$mode" != "update" ]
                then
                        header_install
                        if [ $Lang == "fr" ]
                                then echo "Le fichier de configuration d'une ancienne version a été trouvé";
                                else echo "The configuration file of an old version has been found";
                        fi
                        response=0
                        PTN='^[oOnNyY]$'
                        until [[ $(expr $response : $PTN) -gt 0 ]]
                        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 /tmp/alcasar-conf*
                                fi
                        done
                fi
# Test if update
                if [ -e /tmp/alcasar-conf.tar.gz ] 
                then
                        if [ $Lang == "fr" ]
                                then echo "#### Installation avec mise à jour ####";
                                else echo "#### Installation with update     ####";
                        fi
# Extract the central configuration file
                        tar -xf /tmp/alcasar-conf.tar.gz conf/etc/alcasar.conf 
                        ORGANISME=`grep ORGANISM conf/etc/alcasar.conf|cut -d"=" -f2`
                        mode="update"
                else
                        mode="install"
                fi
                for func in init network gestion AC init_db param_radius param_web_radius param_chilli param_squid param_dansguardian antivirus param_ulogd param_awstats param_dnsmasq BL cron post_install
                do
                        $func
# echo "*** 'debug' : end of function $func ***"; read a
                done
                ;;
        -u | --uninstall)
                if [ ! -e $DIR_DEST_SBIN/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='^[oOnN]$'
                until [[ $(expr $response : $PTN) -gt 0 ]]
                do
                        if [ $Lang == "fr" ]
                                then echo -n "Voulez-vous créer le fichier de configuration de la version actuelle (0/n)? ";
                                else echo -n "Do you want to create the running version configuration file (Y/n)? ";
                        fi
                        read response
                done
                if [ "$reponse" = "o" ] || [ "$reponse" = "O" ] || [ "$response" = "Y" ] || [ "$response" = "y" ]
                then
                        $DIR_SCRIPT/alcasar-conf.sh --create
                else    
                        rm -f /tmp/alcasar-conf*
                fi
# Uninstall the running version
                $DIR_SCRIPTS/sbin/alcasar-uninstall.sh
                ;;
        *)
                echo "Argument inconnu :$1";
                echo "Unknown argument :$1";
                echo "$usage"
                exit 1
                ;;
esac
# end of script