#!/usr/bin/env bash

# Note: we don't just use "apache2ctl" here because it itself is just a shell-script wrapper around apache2 which provides extra functionality like "apache2ctl start" for launching apache2 in the background.
# (also, when run as "apache2ctl <apache args>", it does not use "exec", which leaves an undesirable resident shell process)

: "${APACHE_CONFDIR:=/etc/apache2}"
: "${APACHE_ENVVARS:=$APACHE_CONFDIR/envvars}"
if test -f "$APACHE_ENVVARS"; then
     . "$APACHE_ENVVARS"
fi

# Apache gets grumpy about PID files pre-existing
: "${APACHE_RUN_DIR:=/var/run/apache2}"
: "${APACHE_PID_FILE:=$APACHE_RUN_DIR/apache2.pid}"
rm -f "$APACHE_PID_FILE"

# create missing directories
# (especially APACHE_RUN_DIR, APACHE_LOCK_DIR, and APACHE_LOG_DIR)
for e in "${!APACHE_@}"; do
     if [[ "$e" == *_DIR ]] && [[ "${!e}" == /* ]]; then
        # handle "/var/lock" being a symlink to "/run/lock", but "/run/lock" not existing beforehand, so "/var/lock/something" fails to mkdir
        #   mkdir: cannot create directory '/var/lock': File exists
        dir="${!e}"
        while [ "$dir" != "$(dirname "$dir")" ]; do
             dir="$(dirname "$dir")"
             if [ -d "$dir" ]; then
                break
             fi
             absDir="$(readlink -f "$dir" 2>/dev/null || :)"
             if [ -n "$absDir" ]; then
                mkdir -p "$absDir"
             fi
        done

        mkdir -p "${!e}"
     fi
done

/bin/cp /etc/letsencrypt/live/webdevel.servidortemporal.net/fullchain.pem /etc/ssl/certs/ssl-cert-snakeoil.pem
/bin/cp /etc/letsencrypt/live/webdevel.servidortemporal.net/privkey.pem /etc/ssl/private/ssl-cert-snakeoil.key

exec apache2 -DFOREGROUND "$@" &

chown -R www-data.www-data /var/www

# COMIENZO CRON

# make link to custom location of /etc/cron.d if provided
if [ "${CRON_PATH}" ]; then
    rm -rf /etc/cron.d
    ln -sfTv "${CRON_PATH}" /etc/cron.d
fi

# remove write permission for (g)roup and (o)ther (required by cron)
chmod -R go-w /etc/cron.d

touch /var/log/cron.log

# setting user for additional cron jobs
case $1 in
-u=*|--user=*)
    crontab_user="-u ${1#*=}"
    shift
    ;;
-u|--user)
    crontab_user="-u $2"
    shift 2
    ;;
-*)
    echo "Unknown option: ${1%=*}" > /dev/stderr
    exit 1
    ;;
*)
    crontab_user=""
    ;;
esac

# adding additional cron jobs passed by arguments
# every job must be a single quoted string and have standard crontab format,
# e.g.: start-cron --user user "0 \* \* \* \* env >> /var/log/cron.log 2>&1"
{ for cron_job in "$@"; do echo -e ${cron_job}; done } \
    | sed --regexp-extended 's/\\(.)/\1/g' \
    | crontab ${crontab_user} -

# update default values of PAM environment variables (used by CRON scripts)
env | while read -r line; do  # read STDIN by line
    # split LINE by "="
    IFS="=" read var val <<< ${line}
    # remove existing definition of environment variable, ignoring exit code
    sed --in-place "/^${var}[[:blank:]=]/d" /etc/security/pam_env.conf || true
    # append new default value of environment variable
    echo "${var} DEFAULT=\"${val}\"" >> /etc/security/pam_env.conf
done

# start cron
service cron start

# trap SIGINT and SIGTERM signals and gracefully exit
trap "service cron stop; kill \$!; exit" SIGINT SIGTERM

# start "daemon"
while true
do
    # watch /var/log/cron.log restarting if necessary
    cat /var/log/cron.log & wait $!
done

################ FIN CRON

