#!/bin/bash

##################################################
# Mount dir                                      #
# - /etc/nginx/stream.d                          #
# - /etc/nginx/http.d                            #
# - /var/lib/nginx/html                          #
# - /var/log/nginx                               #
# ENV                                            #
# - GLOBAL_DIRECTIVES                            #
##################################################

set -euo pipefail
export LANG=en_US.UTF-8
trap Quit EXIT

PIDS=
GOT_SIGTERM=
GLOBAL_DIRECTIVES="${GLOBAL_DIRECTIVES:-user nginx;worker_processes auto;}"

function Print {
    local file=/dev/null
    [ '-f' = "$1" ] && file=$2 && shift && shift
    date +"[%F %T] $*" | tee -a $file
}

function Quit {
    local running
    Print killing nginx ...
    nginx -s quit || true
    while running= ; do
        pkill -f sleep && running=1 && Print killing sleep ...
        pkill -f nginx && running=1 && Print killing nginx ...
        [ -z "$running" ] && break
        sleep 1
    done
    Print Container stopped.
    test -n "$GOT_SIGTERM"
}

function ChangeOwner {
    Print Changing file owner ...
    chown nginx:root /var/log/nginx/
}

function SideCar {
    local day= last_day=$(date +%d)
    local md5= last_md5=$(find /etc/nginx/ -type f -name "*.conf" \
        | xargs -I ^ md5sum ^ | md5sum)
    while sleep 8; do
        day=$(date +%d) \
            && [ "$day" != "$last_day" ] \
            && last_day=$day \
            && find /var/log/nginx/ -type f -name "*.log" \
                | xargs -I ^ mv -f ^ ^.$(date +%F -d yesterday) \
            && nginx -s reopen
        md5=$(find /etc/nginx/ -type f -name "*.conf" | xargs -I ^ md5sum ^ \
            | md5sum) \
            && [ "$md5" != "$last_md5" ] \
            && last_md5=$md5 \
            && nginx -tq \
            && Print Reloading nginx conf ... \
            && nginx -s reload
    done
}

function StartProc {
    Print Starting nginx ...
    nginx -g "$GLOBAL_DIRECTIVES" &
    PIDS="$PIDS $!"
    Print Starting nginx sidecar ...
    SideCar &
    PIDS="$PIDS $!"
    Print Nginx started.
}

function Main {
    local pid=
    ChangeOwner
    StartProc
    trap "GOT_SIGTERM=1; Print Got SIGTERM ..." SIGTERM
    while [ -z "$GOT_SIGTERM" ] && sleep 2; do
        for pid in $PIDS; do
            [ ! -e /proc/$pid ] && Print Unexpected error! && exit
        done
    done
}

# Start here
Main

