#!/bin/bash
# Apache2 hook for ee-ips
# This hook generate a file /etc/apache2/conf-available/ee-ips.conf that define:
# - an EE_IPS variable that could be use for instance to filter access to a location:
#   <Location />
#     Require ip ${EE_IPS}
#   </Location>
#
# - a variable IS_FROM_EE set to "1" when remote user access to apache2 resource from an
#   Easter-eggs IP address. It could be use for instance as condition of a RewriteRule:
#
#   RewriteCond %{ENV:IS_FROM_EE} !1
#   RewriteRule ^ - [F]
#
# cSpell:words a2enconf setenvif ipmatch

set -e

if \
    [[ ! -d /etc/apache2/conf-available ]] \
    || ! which a2enconf > /dev/null 2>&1 \
    || ! which apache2ctl > /dev/null 2>&1
then
    [[ "$1" != "detect" ]] && echo "Apache2 seem not installed"
    exit 1
fi
[[ "$1" == "detect" ]] && exit 0

# shellcheck source=/dev/null
source /usr/share/ee-ips/data/ee-ips.bash

# shellcheck source=/dev/null
source /usr/lib/ee-ips/helpers

cat << EOF > /etc/apache2/conf-available/ee-ips.conf
# Auto-generated file by ee-ips debian package
# All changes will be override on next install/upgrade

Define EE_IPS "${EE_IP4[*]} ${EE_IP6[*]}"

<IfModule mod_setenvif.c>
    SetEnvIfExpr "%{REMOTE_ADDR} in { \\
       '$( implode "', '" "${EE_IP4[@]}" )', \\
       '$( implode "', '" "${EE_IP6[@]}" )' \\
    }" IS_FROM_EE=1
</IfModule>
EOF
echo "Apache configuration file /etc/apache2/conf-available/ee-ips.conf updated"

if [[ -e "/etc/apache2/conf-enabled/ee-ips.conf" ]]; then
    a2enconf ee-ips
    echo "Apache configuration file enabled"
fi

apache2ctl configtest || exit 1  # cSpell:words configtest

[[ "$( systemctl is-active apache2 )" == "active" ]] && \
    systemctl reload apache2 && \
    echo "Apache2 configuration reloaded"
