#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

function error() {
	echo -e "\033[31m$1\033[0m"
}

function warning() {
	echo -e "\033[33m$1\033[0m"
}

OS="`getos`"

warning "Detected ${OS} OS"

HOMEDIR="/var/lib/postgresql"
DATADIR="${HOMEDIR}/10/main"
CONFDIR=""
BINDIR="/usr/lib/postgresql/10/bin"
INITDB="${BINDIR}/initdb"
PGHBA="${CONFDIR}/pg_hba.conf"
POSTGRES_SERVICE_NAME="postgresql@`basename $(dirname \"${DATADIR}\")`-`basename \"${DATADIR}\"`.service"

if [ ${UID} != 0 ]; then
	error "This script must be ran as root"
	exit 1
fi

if [ ! -d "${DATADIR}" ]; then
	# stop postgresql service and initialize the data directory
	/opt/dosis2/bin/os-support-service stop "${POSTGRES_SERVICE_NAME}"
	su -l postgres -c "\"${INITDB}\" -D \"${DATADIR}\""
else
	warning "PostgreSQL Data Directory \"${DATADIR}\" already exists; will not initialize database"
fi

if [ ! -f "${HOMEDIR}/.bash_profile" ]; then
	echo "Creating Bash Profile For Postgres User"
	cat <<EOF > "${HOMEDIR}/.bash_profile"
[ -f /etc/profile ] && source /etc/profile
PGDATA="${DATADIR}"
export PGDATA
EOF
fi

if [ "${CONFDIR}" != "" ]; then
	# create basic configuration directories
	install -m 0755 -o postgres -g postgres -dv "${CONFDIR}"
	install -m 0755 -o postgres -g postgres -dv "${CONFDIR}/conf.d"

	# move over some configuration files
	mv "${DATADIR}/postgresql.conf" "${CONFDIR}/."
	mv "${DATADIR}/pg_hba.conf" "${CONFDIR}/."
	mv "${DATADIR}/pg_ident.conf" "${CONFDIR}/."

	# create environment
	cat << EOF > "${CONFDIR}/environment"
# environment variables for postgres processes
# This file has the same syntax as postgresql.conf:
#  VARIABLE = simple_value
#  VARIABLE2 = 'any value!'
# I. e. you need to enclose any value which does not only consist of letters,
# numbers, and '-', '_', '.' in single quotes. Shell commands are not
# evaluated.
EOF
	chmod 0600 "${CONFDIR}/environment"
	chown postgres.postgres "${CONFDIR}/environment"

	# create pg_ctl.conf
	cat << EOF > "${CONFDIR}/pg_ctl.conf"
# Automatic pg_ctl configuration
# This configuration file contains cluster specific options to be passed to
# pg_ctl(1).

pg_ctl_options = ''
EOF
	chmod 0600 "${CONFDIR}/pg_ctl.conf"
	chown postgres.postgres "${CONFDIR}/pg_ctl.conf"

	# create start.conf
	cat << EOF > "${CONFDIR}/start.conf"
# Automatic startup configuration
#   auto: automatically start the cluster
#   manual: manual startup with pg_ctlcluster/postgresql@.service only
#   disabled: refuse to start cluster
# See pg_createcluster(1) for details. When running from systemd,
# invoke 'systemctl daemon-reload' after editing this file.

auto
EOF
	chmod 0600 "${CONFDIR}/start.conf"
	chown postgres.postgres "${CONFDIR}/start.conf"

	# create an options file for postmaster to link the config file
	cat << EOF > "${DATADIR}/postmaster.opts"
${BINDIR}/postgres "-D" "${DATADIR}" "-c" "config_file=${CONFDIR}/postgresql.conf"
EOF
	chmod 0600 "${DATADIR}/postmaster.opts"
	chown postgres.postgres "${DATADIR}/postmaster.opts"

	# change permissions on postgresql.conf so that pg_wrapper can read it
	chmod a+r "${CONFDIR}/postgresql.conf"
fi

# add default pg_hba.conf file
cat << EOF > "${PGHBA}"
# DOSIS CONFIGURATION
# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD
local   all         all                               trust
host    all         all         127.0.0.1/32          trust
host    all         all         ::1/128               trust

# Add all team dafes explicitly here with dpg and trust
# See example below...
#host    dosis2       dpg         192.168.0.0/32        trust

# Entries to support remote
host    all          dsuper      0.0.0.0/0             password
host    dosis2       dafe_get    10.120.0.0/16         password
host    dosis2       dafe_get    10.121.0.0/16         password
host    dosis2       dafe_get    10.106.0.0/16         password
host    dosis2       dafe_get    10.180.0.0/16         password
host    dosis2       dafe_get    10.190.0.0/16         password
host    dosis2       dafe_get    10.200.0.0/16         password
EOF
chmod 0600 "${PGHBA}"
chown postgres.postgres "${PGHBA}"

echo "Patching /var/log/postgresql"
chown postgres "/var/log/postgresql"

/usr/share/dosis2/bin/update-postgresql-conf

sleep 5

if [ -d "/opt/dosis2/.private" ]; then
	echo "Copying private keys"
	cp /opt/dosis2/.private/*-pmis.key "${DATADIR}/."
	chown postgres.postgres "${DATADIR}/"*-pmis.key
	chmod 0400 "${DATADIR}/"*-pmis.key
fi

echo "Enabling and Restarting PostgreSQL Service"
/opt/dosis2/bin/os-support-service enable "${POSTGRES_SERVICE_NAME}"
/opt/dosis2/bin/os-support-service restart "${POSTGRES_SERVICE_NAME}"
