#!/bin/sh
set -e

STDERR () {
    cat - 1>&2
}

if [ "$1" = 'postgres' ]; then
    # exit if postgres directory does not already exist
    [ -d "$PGDATA" ] || (echo "PGDATA=$PGDATA does not exist" | STDERR && exit 1)
    echo '##### chown'
    chown -R postgres "$PGDATA"

    # if data directory does not have any files
    # initialize database in its place
    if [ -z "$(ls -A "$PGDATA")" ]; then
        gosu postgres /usr/lib/postgresql/$PG_VERSION/bin/initdb --encoding="UTF8"

        sed -ri "s/^#(listen_addresses\s*=\s*)\S+/\1'*'/" "$PGDATA"/postgresql.conf

        { echo; echo 'host all all 0.0.0.0/0 md5'; } >> "$PGDATA"/pg_hba.conf
        echo '##### start postgresql for cstl init'
        exec gosu postgres /usr/lib/postgresql/$PG_VERSION/bin/"$@" -D "$PGDATA" -c config_file="$PGDATA"/postgresql.conf &
        # Perform all actions as $POSTGRES_USER
        export PGUSER="$POSTGRES_USER"
		sleep 5
        echo 'creating cstl user'
        gosu postgres createuser -d -r -s cstl
        echo 'created cstl user'
        gosu postgres createdb -O cstl -E UTF8 -T template0 constellation
        echo 'creating cstl db'

        # alter cstl user and role
        gosu postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE constellation to cstl; ALTER ROLE cstl WITH PASSWORD 'admin'"
        echo 'altered cstl user'

		# create rhomeo database for referential geodata
		echo 'creating rhomeo user'
        gosu postgres createuser -d -r -s rhomeo
        echo 'created rhomeo user'
        gosu postgres createdb -O rhomeo -E UTF8 -T template0 referential
        echo 'creating referential db'
        gosu postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE referential to rhomeo; ALTER ROLE rhomeo WITH PASSWORD 'espaces naturels !'"
        echo 'altered rhomeo user'
		echo 'creating postgis extension'
        gosu postgres psql -d referential -c "CREATE EXTENSION postgis;"
        echo 'created postgis extension'

		
        kill -INT `head -1 "$PGDATA"/postmaster.pid`
        sleep 5
        echo 'kill postgresql'
    fi

fi

# command is a postgres executable hence execute it as postgres user
if [ -x /usr/lib/postgresql/"$PG_VERSION"/bin/"$1" ]; then
    echo "executing as postgres user"
    exec gosu postgres /usr/lib/postgresql/$PG_VERSION/bin/"$@" -D "$PGDATA" -c config_file="$PGDATA"/postgresql.conf
else
  echo "executing what else"
    exec "$@"
fi

