#!/bin/bash

##################################################
# Mount file                                     #
# - /etc/my.cnf                                  #
# - /etc/zabbix/zabbix_server.conf               #
# Mount dir                                      #
# - /etc/nginx/http.d                            #
# - /var/log/mysql                               #
# - /var/lib/mysql                               #
# - /var/lib/mysql-bin                           #
# - /var/log/nginx                               #
# - /var/log/php7                                #
# - /var/log/zabbix                              #
# ENV                                            #
# - GLOBAL_DIERECTIVES                           #
##################################################

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

PIDS=
GOT_SIGTERM=
LOG_DIR='/var/log/mysql'
DATA_DIR='/var/lib/mysql'
BINLOG_DIR='/var/lib/mysql-bin'
INIT_FLAG=${INIT_FLAG:-}
SOCK_FILE='/run/mysqld/mysqld.sock'
PID_FILE='/run/mysqld/mysqld.pid'
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
    while running= ; do
        pkill -f sleep         && running=1 && Print killing sleep ...
        pkill -f nginx         && running=1 && Print killing nginx ...
        pkill -f php-fpm7      && running=1 && Print killing php-fpm7 ...
        pkill -f zabbix_server && running=1 && Print killing zabbix_server ...
        pkill -f mysqld        && running=1 && Print killing mysqld ...
        [ -z "$running" ] && break
        sleep 1
    done
    Print Container stopped.
    test -n "$GOT_SIGTERM"
}

function RestoreConf {
    ! ls /etc/nginx/http.d/*.conf 2>/dev/null | grep -Eq '(zabbix|zbx)' \
        && Print Restoring /etc/nginx/http.d/zabbix.conf ... \
        && cp /usr/share/zabbix/nginx.conf /etc/nginx/http.d/zabbix.conf
    [ ! -e /etc/zabbix/zabbix_proxy.conf ] \
        && Print Restoring /etc/zabbix/zabbix_proxy.conf ... \
        && cp /usr/share/zabbix/zabbix_proxy.conf /etc/zabbix/zabbix_proxy.conf
    [ ! -e /etc/zabbix/zabbix_server.conf ] \
        && Print Restoring /etc/zabbix/zabbix_server.conf ... \
        && cp /usr/share/zabbix/zabbix_server.conf /etc/zabbix/zabbix_server.conf
    return 0
}

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 10; do
        day=$(date +%d) \
            && [ "$day" != "$last_day" ] \
            && last_day=$day \
            && find /var/log/nginx/ -type f -name "*.log" \
                | xargs -I ^ mv ^ ^.$(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 InitDB {
    rm -f $SOCK_FILE $PID_FILE
    chown -R mysql:mysql $LOG_DIR $BINLOG_DIR $DATA_DIR
    if [ ! -d "$DATA_DIR/mysql" ]; then
        Print Installing database ...
        mysql_install_db --user=mysql > /dev/null
        INIT_FLAG=1
    fi
}

function StartProc {
    Print Starting mysql ...
    mysqld -u mysql &
    PIDS="$PIDS $!"
    while sleep 1; do
        [ -e $SOCK_FILE ] && break || echo -n .
        [ ! -e /proc/$! ] && echo && Print unexpected error! && exit
    done
    echo
    if [ -n "$INIT_FLAG" ]; then
        Print Securing database ...
        mysql_secure_installation <<< "$(echo -e '\nn\nn\n\n\n\n\n')" > /dev/null
        Print Creating zabbix db and user ...
        mysql -e "CREATE DATABASE zabbix DEFAULT CHARSET UTF8 COLLATE UTF8_BIN"
        mysql -e "CREATE USER zabbix@localhost"
        mysql -e "GRANT ALL ON zabbix.* TO zabbix@localhost"
        Print Importing zabbix schema.sql ...
        mysql -Dzabbix < /usr/share/zabbix/database/mysql/schema.sql
        Print Importing zabbix images.sql ...
        mysql -Dzabbix < /usr/share/zabbix/database/mysql/images.sql
        Print Importing zabbix history_pk_prepare.sql ...
        mysql -Dzabbix < /usr/share/zabbix/database/mysql/history_pk_prepare.sql
        Print Importing zabbix double.sql ...
        mysql -Dzabbix < /usr/share/zabbix/database/mysql/double.sql
        Print Importing zabbix data.sql ...
        mysql -Dzabbix < /usr/share/zabbix/database/mysql/data.sql
        if sql_files="$(ls $DATA_DIR/init_sql/*.sql 2>/dev/null)"; then
            Print Importing the sql files ...
            for sql_file in $sql_files; do
                 Print Importing $sql_file ...
                 mysql < $sql_file
            done
            Print Imported all sql files successfully.
        fi
    fi
    Print MySQL is ready for connections.

    RestoreConf

    Print Starting php ...
    php-fpm81 -F -y /etc/php81/php-fpm.conf &
    PIDS="$PIDS $!"

    Print Starting zabbix ...
    zabbix_server -f &
    PIDS="$PIDS $!"

    Print Starting nginx ...
    nginx -g "$GLOBAL_DIRECTIVES" &
    PIDS="$PIDS $!"

    Print Starting nginx sidecar ...
    SideCar &
    PIDS="$PIDS $!"

    Print All components started.
}

function Main {
    local pid=
    InitDB
    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

