#!/bin/bash

############################################
# Script eole-common
############################################

action=$1

. /usr/lib/eole/ihm.sh

systemctl enable ferme-firewall

#recharger les fichiers override
systemctl daemon-reload
CreoleRun "systemctl daemon-reload" all yes yes

#recharger les profiles apparmor
service apparmor reload
#CreoleRun "service apparmor reload" all yes yes --> FIXME #20176

#test si le réseau est configuré sinon renvoie une erreur (#1100)
adresse_ip_eth0=`CreoleGet adresse_ip_eth0`
if [ "$adresse_ip_eth0" = "" ]; then
        EchoRouge "Impossible de déterminer l'adresse réseau \"adresse_ip_eth0\"."
        EchoRouge "Redemarrage du reseau"
        service networking restart
        EchoRouge "#######################################################################"
        EchoRouge "# Veuillez relancer $action"
        EchoRouge "#######################################################################"
        exit 1
fi

bonding_is_active=$(CreoleGet bonding_is_active)
if [ "$bonding_is_active" != "oui" ]
then
    lsmod | grep bonding -q && rmmod bonding
fi

#pour rsyslog
LOG_BASE="/var/log/rsyslog"
if [[ ! -d $LOG_BASE ]]; then
    mkdir -p $LOG_BASE
    chown -R syslog:adm $LOG_BASE
    CreoleService rsyslog restart
fi

#pour l'envoi des logs (#11404)
if [ "$(CreoleGet activer_envoi_logs non)" = oui ];then
    if [ ! -d "${LOG_BASE}/queues" ];then
        mkdir -p ${LOG_BASE}/queues
        chown syslog:adm ${LOG_BASE}/queues
        CreoleService rsyslog restart
    fi
fi

#pour les logs de certains outils
mkdir -p /var/log/eole

#pour les logs avec noms non-conventionnels (#33848)
/usr/sbin/eole-purge-logs

#pour logrotate
LOG_TYPES="local remote"
LOGROTATE_CONF_D=/etc/logrotate.d
LOGROTATED_DIRS=''

# Clean generated files
for log_type in ${LOG_TYPES}
do
	[ -e ${LOGROTATE_CONF_D}/generated_${log_type}_rules ] \
	    && rm -f ${LOGROTATE_CONF_D}/generated_${log_type}_rules
done

# Get all directories referenced in logrotate configuration
for log_file in $(sed -ne '/^\/.*\.log/ p' ${LOGROTATE_CONF_D}/* 2> /dev/null); do
    if [ ${log_file} != '{' ]; then
        log_dir=$(dirname ${log_file})
        LOGROTATED_DIRS="${LOGROTATED_DIRS:+${LOGROTATED_DIRS}$'\n'}${log_dir}"
    fi
done

# Deduplicate directory list
LOGROTATED_DIRS=$(echo "$LOGROTATED_DIRS" | sort -u)

vpn_service() {
    ACTION=$1
    HA_RSC_FILE="/etc/ha.d/.rsc_list"
    if [ -e $CONFRVP ] && [ "$install_rvp" = "oui" ]
    then
        INITRVP_ACTION="yes"
        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
        if [ "$INITRVP_ACTION" == "yes" ]
        then
            service $INITRVP $ACTION
        fi
    fi
}

get_not_rotated_log_files() {
	local base_dir="${1}"
	local not_rotated=""
	[ -d "${base_dir}" ] || return
	for log_file in $(find ${base_dir} -type f -name '*.log')
	do
		log_dir=$(dirname ${log_file})
		if [[ ! "$LOGROTATED_DIRS" =~ ${log_dir} ]]; then
			# Avoid newline when ${not_rotated} is empty
			not_rotated="${not_rotated:+${not_rotated}$'\n'}${log_file}"
		fi
	done
	echo -e "${not_rotated}"
}

gen_globs_from_files() {
	local levels='\(panic\|emerg\|crit\|err\|error\|alert\|warn\|warning\|info\|notice\|debug\)'
	echo "$@" | sed -e "s,\.${levels}\.,.\*.," | sort -u
}

generate_logrotate_rules() {
	local GLOBBING=$-
	set -f # Disable globbing
	local rules_file="${1}"
	shift # strip first parameter
	local globs="$@"
	local globsuniq=$(echo $globs | sort -u)
	local logs=""
	# Avoid expanding globs
	for log_glob in ${globsuniq}
	do
		[ -n "${log_glob}" ] || continue
		logs="${logs:+${logs}$'\n'}${log_glob}"
	done
	if [ -n "${logs}" ]; then
		cat >> ${rules_file} <<EOF
$logs {
	missingok
	daily
	rotate 366
	compress
	sharedscripts
	postrotate
		/usr/lib/rsyslog/rsyslog-rotate > /dev/null
	endscript
}
EOF
	fi
	[[ "${GLOBBING}" =~ f ]] && set +f

}

for log_type in ${LOG_TYPES}
do
	rotate_conf_file=${LOGROTATE_CONF_D}/generated_${log_type}_rules
	log_dir=${LOG_BASE}/${log_type}

	[ -f "${rotate_conf_file}" ] && rm -f "${rotate_conf_file}"

	echo "# Rules automatically generated" >> ${rotate_conf_file}
	# Do not forget the double quoting or globs will be expanded
	FILES="$(get_not_rotated_log_files ${log_dir})"
	GLOBS="$(gen_globs_from_files "${FILES}")"
	generate_logrotate_rules ${rotate_conf_file} "${GLOBS}"
done

#commente HISTSIZE et HISTFILESIZE car ce sont des paramétrages en lecture seule
sed -i 's/^HISTSIZE/#HISTSIZE/g' /root/.bashrc
sed -i 's/^HISTFILESIZE/#HISTFILESIZE/g' /root/.bashrc

#prend en compte le template 10-console-messages.conf
cat /etc/sysctl.d/10-console-messages.conf | sysctl -p - > /dev/null

#regénération des règles iptables
IS_AMON=$(CreoleGet type_amon non)
MODE_CONTENEUR_ACTIF=$(CreoleGet mode_conteneur_actif)
if [ $IS_AMON != "non" ]
then
    INITRVP='strongswan-starter'
    install_rvp=$(CreoleGet install_rvp non)
    if [ "$install_rvp" = "oui" ]
    then
        if [ "$(CreoleGet sw_database_mode)" = "oui" ]
        then
            CONFRVP='/etc/ipsec.d/ipsec.db'
        else
            CONFRVP='/etc/ipsec.secrets'
        fi
    else
        CONFRVP=''
    fi
    vpn_service start > /dev/null
    [ -f /lib/systemd/system/named.service ] && CreoleService named start > /dev/null
    [ $MODE_CONTENEUR_ACTIF = "oui" ] && CreoleService -c addc named start > /dev/null
fi
echo -n "Génération des règles de pare-feu"
. /usr/share/eole/firewall.start
if [ $? -ne 0 ]; then
    echo
    EchoRouge "Erreur à la génération des règles de pare-feu"
    rm -f /etc/eole/iptables
    rm -f /etc/eole/ipset
    exit 1
fi
echo
#on repasse en mode forteresse avant le démarrage du service
if [ $IS_AMON != "non" ]
then
    [ -f /lib/systemd/system/named.service ] && CreoleService named stop > /dev/null
    vpn_service stop > /dev/null
fi
/usr/sbin/ferme.firewall

#notamment pour Era (#8106)
mkdir -p /root/.local/share

#activation/désactivation de la séquence ctrl-alt-suppr (#17337)
TARGET="/etc/systemd/system/ctrl-alt-del.target"
if [ $(CreoleGet activer_ctrl_alt_suppr) = "oui" ];then
    [ -L $TARGET ] && rm -f $TARGET
else
    [ ! -e $TARGET ] && ln -nsf /dev/null $TARGET
fi

#reinitialisation de toutes les erreurs
systemctl reset-failed

#suppression d'un fichier généré par dhclient pré-instance (#21862)
rm -f /var/lib/ntpdate/default.dhcp
rm -f /var/lib/ntp/ntp.conf.dhcp

#désactiver certbot
systemctl disable certbot.service certbot.timer

# La demande de certificat LE n'a pas été faite, il faut donc creer un fichier valide
server_full_chain_pem=$(CreoleGet server_full_chain_pem)
if [ ! -f "$server_full_chain_pem" ]; then
    cp -a "$(CreoleGet server_cert)" "$server_full_chain_pem"
fi

exit 0
