#!/bin/bash

##################################################
# Mount dir                                      #
# - /var/lib/pgsql                               #
# - /var/log/pgsql                               #
# - /etc/pgsql/conf.d                            #
##################################################

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

PIDS=
GOT_SIGTERM=
LOG_DIR=/var/log/pgsql
DATA_DIR=/var/lib/pgsql
VERSION=$VERSION

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

function Quit {
    Print killing pgsql ...
    su - postgres -c "pg_ctl stop" || true
    while :; do
        pkill -x postmaster && Print killing postmaster ... || break
        sleep 2
    done
    Print Container stopped.
    test -n "$GOT_SIGTERM"
}

function Init {
    chown -R postgres:postgres $LOG_DIR $DATA_DIR
    if [ -z "$(ls $DATA_DIR)" ]; then
        Print Initing pgsql db files ...
        su - postgres -c "initdb --pgdata=$DATA_DIR --locale=en_US.UTF-8"
    else
        Print Checking pgsql db dir ...
        su - postgres -c "postgresql-$VERSION-check-db-dir $DATA_DIR"
    fi
}

function StartProc {
    Print Starting pgsql ...
    local sock="/tmp/.s.PGSQL.$(su - postgres -c 'postgres -C port')"
    rm -f $sock
    su - postgres -c postgres &
    PIDS="$PIDS $!"
    while sleep 1; do
        [ -e $sock ] && break || echo -n .
        [ ! -e /proc/$! ] && echo && Print unexpected error! && exit
    done
    echo
    Print PGSQL is ready for connections.
}

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

