#!/usr/bin/env bash

# Safer command execution:
#   -E If set, the ERR trap is inherited by shell functions.
#   -e Exit immediately if a command exits with a non-zero status.
#   -u Treat unset variables as an error when substituting.
#   -o pipefail the return value of a pipeline is the status
#        of the last command to exit with a non-zero status,
#        or zero if no command exited with a non-zero status
set -Eeuo pipefail

# Script command to be executed
CMD=${1:-help}

# Process some known arguments ...
case $CMD in
  help)
    printf "•••••••••••••••••••••••••••••••••••••••"
    printf "•• Docker Entrypoint Script          ••"
    printf "••• Known commands:                  ••"
    printf "•••• help: show this help message    ••"
    printf "•••• run-idle: run idle (sleep) loop ••"
    printf "•••• run-http: run http server       ••"
    printf "•••• \$@: execute arbitrary commands ••"
    printf "•••••••••••••••••••••••••••••••••••••••"
    ;;

  run-idle)
    echo "Executing [run-idle] command..."

    # Run idle loop
    sleep infinity
    ;;

  run-http)
    echo "Executing [run-http] command..."

    # Apache gets grumpy about PID files pre-existing
    rm -f /usr/local/apache2/logs/httpd.pid

    # Read apache2 env vars
    export APACHE_CONFDIR=/etc/apache2/
    source /etc/apache2/envvars

    # Cleanup and compile apache default virtual host
    rm -rf /etc/apache2/sites-{available,enabled}/*.conf
    envsubst < /etc/apache2/sites-available/000-default.conf.tpl > /etc/apache2/sites-available/000-default.conf

    # Enable default virtual host
    a2ensite 000-default

    # Run apache2 in foreground
    /usr/sbin/apachectl -DFOREGROUND
    ;;
esac

# Otherwise just run the specified command
CMD_STRING=$(echo "$*" | tr '\n' ' ')
printf "Executing entrypoint command [%s]\n" "${CMD_STRING::-1}"
exec "${@}"
