#!/bin/bash

# This script is executed during apache2 startup.
# It removes all non-valid ip addresses contained in the ports.conf file.
# This script has been added to fix the restart of apache2 when a VCA node is down (see TL-8593).

# Location of the ports.conf file
ports_conf_path="/etc/apache2/ports.conf"

# Search valid ip addresses on this machine
valid_ips=`ip a | grep -oP 'inet \K(\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]\b)'`

# Search ip addresses mentionned in the ports.conf file
current_ips=`grep -oP 'Listen \K(\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]\b)' ${ports_conf_path} | sort | uniq`

has_listen_80=`grep 'Listen 80' ${ports_conf_path}`

filecontent="# If you just change the port or add more ports here, you will likely also
# have to change the VirtualHost statement in
# /etc/apache2/sites-enabled/000-default.conf

Listen 80

<IfModule ssl_module>
        Listen 443
</IfModule>

<IfModule mod_gnutls.c>
        Listen 443
</IfModule>
"

# Check if we have VCA nodes
vca_nodes=false
for ipv in ${valid_ips}
do
    if [[ $ipv =~ 172.31.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]).254 ]]
    then
        vca_nodes=true
    fi
done

if [ "${vca_nodes}" = true ]
then
    # Delete all ip addresses contained in the ports.conf file
    for ipc in ${current_ips}
    do
        sed -i "/${ipc}/d" ${ports_conf_path}
    done

    
    if [ "${has_listen_80}" = "" ]
    then
        echo "${filecontent}" > ${ports_conf_path}
    fi
fi
