#!/bin/sh

#
# Transition script for bastion systemd trip
#


RETVAL=0
[ "$TERM" = "dumb" ] && export TERM=eole
. /lib/lsb/init-functions

# Don't regen bastion rules if server is not instanciate
[ -f /etc/eole/bastion.conf ] && . /etc/eole/bastion.conf || exit 0

export TPUT=/usr/bin/tput
export EXPR=/usr/bin/expr
#test si TPUT est utilisable
if [ ! "$TERM" = "" ] && $TPUT hpa 60 >/dev/null 2>&1 && $TPUT setaf 1  >/dev/null 2>&1; then
    FANCYTTY=1
    COLS=`$TPUT cols`
    if [ "$COLS" ] && [ "$COLS" -gt 6 ]; then
        COL=`$EXPR $COLS - 7`
    else
    COLS=80
        COL=73
    fi
    export COL
else
    FANCYTTY=0
fi
CACHE='/etc/eole/iptables'
CACHEMOD='/etc/eole/bastion-modules'
CACHESET='/etc/eole/ipset'
CACHEINCLUSION='/etc/eole/inclusion_statique'
TCPWRAPPER='/etc/eole/hosts.allow'
TCPWRAPPER_DEST='/etc/hosts.allow'

INITQOS='/usr/share/eole/sbin/qoseole'
CONFQOS='/etc/qoseole.conf'
LOCKQOS='/var/lock/qoseole'
INITRVP='strongswan-starter'
HA_RSC_FILE="/etc/ha.d/.rsc_list"
if [ "$install_rvp" = "oui" ]
then
    if [ "$sw_database_mode" = "oui" ]
    then
    CONFRVP='/etc/ipsec.d/ipsec.db'
    else
    CONFRVP='/etc/ipsec.secrets'
    fi
else
    CONFRVP=''
fi
INITAGR='/usr/share/eole/sbin/agregation'
CONFAGR='/etc/agregation.conf'
LOCKAGR='/var/lock/agregation'
SOCKETLOG='/run/systemd/journal/syslog'

[ "$TERM" = "dumb" ] && export TERM="eole"

logit() {
    # log dans syslog
    /usr/bin/logger -u "$SOCKETLOG" -t "bastion" -p local2.info "$1"
}
logit2(){
    # log dans syslog et sur la console
    FAILURE=$2
    logit "$1"
    log_begin_msg "$1"
    if [ "$FAILURE" = "failed" ]; then
        log_end_msg 1
    fi
}
test_iptables(){
    if [ ! -x /sbin/iptables ];then
        MSG="Erreur : /sbin/iptables non exécutable !"
        logit2 "$MSG" "failed"
        exit 1
    fi
    iptables -nL >/dev/null
    if [ $? -ne 0 ];then
        MSG="Erreur iptables, vérifiez le noyau Linux utilisé par le serveur"
        logit2 "$MSG" "failed"
        exit 1
    fi
}

firewall_start() {
    test_iptables
    if [ ! -x /usr/share/eole/firewall.start ]
    then
        logit2 "Pas de script permettant la prise en compte des règles de pare-feu" "failed"
        return 1
    fi
    echo -n " * Regénération des règles de pare-feu"
    . /usr/share/eole/firewall.start
    RETVAL=$?
    log_end_msg $RETVAL

    return $RETVAL
}
start() {
    if [ ! -e $CACHE ]; then
        MSG="Erreur : pas de règle de pare-feu en cache, lancer $0 regen"
        logit2 "$MSG" "failed"
        stop
        exit 1
    fi
    MSG="Restauration des règles de pare-feu en cache"
    logit2 "$MSG"

    test_iptables
    [ -f $CACHEMOD ] && sh $CACHEMOD
    [ -f $CACHESET ] && ipset restore -exist < $CACHESET
    iptables-restore < $CACHE
    RETVAL=$?
    [ -f "$CACHEINCLUSION" ] && sh "$CACHEINCLUSION"
    if [ "$mode_conteneur_actif" = "oui" ]
    then
        CreoleRun "service bastion start" all no yes
    fi
    [ -f $TCPWRAPPER ] && /bin/cp -f $TCPWRAPPER $TCPWRAPPER_DEST
    #rules outside bastion scope
    /bin/run-parts /usr/share/eole/bastion/post_cache
    log_end_msg $RETVAL
    if [ $RETVAL -eq 0 ]; then
        #lancement de la qos si activée
        if [ -e $CONFQOS ] && [ -x $INITQOS ]
        then
            logit "Mise en place des règles de QOS"
             $INITQOS start
        fi
        #lancement de l'agrégation si activée
        if [ -e $CONFAGR ] && [ -x $INITAGR ]
        then
            logit "Mise en place des règles d'agrégation"
            $INITAGR start
        fi
        #lancement du rvp si activé
        ## LE RVP DOIT ETRE LANCE EN DERNIER !!!
        if [ -e $CONFRVP ] && [ "$install_rvp" = "oui" ]
        then
            INITRVP_ACTION="yes"
            # Look if VPN is managed by Pacemaker
            if [ -e $HA_RSC_FILE ]
            then
                while read LINE
                do
                    SCE=$(echo "$LINE"|cut -d " " -f3)
                    if [ "$SCE" == "$INITRVP" ]
                    then
                        echo "HA STRONGSWAN"
                        INITRVP_ACTION="no"
                        break
                    fi
                done< $HA_RSC_FILE
            fi
            # Stop VPN to be sure start action adds routes
            # and specifics iptables rules for VPN
            #  * It will start automatically if managed by Pacemaker
            service $INITRVP stop
            # Start VPN if not managed by Pacemaker
            if [ "$INITRVP_ACTION" == "yes" ]
            then
                logit "Mise en place des règles RVP"
                service $INITRVP start
            fi
        fi
    else
        exit 1
    fi
    return $RETVAL
}

stopother() {
    # arrêt des autres programmes gérés par bastion
    if [ -e $LOCKQOS ]
    then
        logit "Arrêt des règles de QOS"
        $INITQOS stop
    fi
    if [ -e $LOCKAGR ]
    then
        logit "Arrêt des règles d'agrégation"
        $INITAGR stop
    fi
    ## LE RVP DOIT ETRE ARRETE EN DERNIER (juste avant le flush iptables)
    if [ -e $CONFRVP ] && [ "$install_rvp" = "oui" ]
    then
        service $INITRVP stop
    fi
}

stop() {
    silent=$1
    logit "Stopping firewall: bastion"
    if [ ! -x /usr/sbin/ferme.firewall ]
    then
        logit2 "pas de script permettant la suppression des règles de pare-feu" "failed"
        return 1
    fi
    test_iptables
    /usr/sbin/ferme.firewall $silent
    RETVAL=$?

    if [ "$mode_conteneur_actif" = "oui" ]
    then
        CreoleRun "service bastion stop" all no yes
    fi

    log_end_msg $RETVAL
    stopother
    return $RETVAL
}

case "$1" in
  start)
	if [ "${2}" != "--systemd" ]
	then
		logit2 "'bastion start' interdit, utiliser 'service bastion start'"
	else
		start
	fi
    ;;

  stop)
	if [ "${2}" != "--systemd" ]
	then
		logit2 "'bastion stop' interdit, utiliser 'service bastion stop'"
	else
		stop
	fi
    ;;

  regen|restart)
	if [ $1 = "restart" ]
	then
		logit2 "L'option 'restart' est obsolète utiliser : "
		logit2 "   'service bastion restart' pour relancer le service"
		logit2 "   'bastion regen' pour regénérer et appliquer les règles du pare-feu"
	fi

    stop yes

    firewall_start
    RETVAL=$?
    MSG="Mise en cache des règles de pare-feu"
    if [ $RETVAL -eq 0 ]; then
        logit2 "$MSG"
        log_end_msg 0
        start
    else
        if [ -f $CACHE ]; then
            MSG="$MSG (utiliser 'CreoleService bastion restart' pour appliquer l'ancien cache)"
            logit2 "$MSG" "failed"
        fi
        stop
    fi
  ;;

  *)
    echo "Usage: $0 regen"
    exit 1
esac

exit 0
