#!/usr/bin/env bash
set -e;

# Initialize PostgreSQL
echo "## Initializing PostgreSQL databases and tables..."

# Setting /tmp to 777 with sticky bit for initdb to work properly
# Fix for bnc#919520
echo "## Setting /tmp to 777 with sticky bit..."
chmod a+trwx /tmp;

PG_DIR=/var/lib/pgsql
PG_DATADIR=$PG_DIR/data
PG_CONF=$PG_DATADIR/postgresql.conf

LANG_SYSCONFIG=/etc/locale.conf;
PG_LANG=$(test -f $LANG_SYSCONFIG && . $LANG_SYSCONFIG && echo ${POSTGRES_LANG:-$LANG});

install -d -o postgres -g postgres -m 700 ${PG_DATADIR};
su - postgres -c "initdb --locale=$PG_LANG --auth='trust' --auth-host='trust' --auth-local='trust' $PG_DATADIR";

# Start PostgreSQL without networking
echo "## Starting PostgreSQL..."
pg_ctl start -o "\"-c listen_addresses=''\"" -s -w -D $PG_DATADIR

#Create wwwrun user
psql "--command=\"CREATE USER root WITH PASSWORD 'root'\"";

#Create wwwrun databases
psql "--command=\"CREATE DATABASE root WITH OWNER = root\"";
#Create gis databases
psql "--command=\"CREATE DATABASE gis WITH OWNER = root\"";

psql "--dbname=gis --command=\"CREATE EXTENSION hstore; CREATE EXTENSION postgis;\"";

# Stop PostgreSQL service (for uncontained builds)
echo "## Stopping PostgreSQL..."
pg_ctl stop -s -D $PG_DATADIR -m fast


echo "## Configuring PostgreSQL to auto-start on boot..."
systemctl enable postgresql;
systemctl start postgresql;