#!/bin/bash

. ${TOOLKIT}-functions.sh

datadir=`jtconf pgsql.datadir`	|| exit_missing_define "pgsql.datadir"
release=`jtconf pgsql.release`	|| exit_missing_defint "pgsql.release"

distdir=/var/lib/postgresql/$release/main

[ -f $datadir/global/pg_control ] || {
	create_dir $datadir postgres:postgres 755 || exit $?
	echo -n "  populate datadir with default (distrib) files ... "
	mirror -f $distdir $datadir >$RUNDIR/tmp.err 2>&1 || {
		status=$?
		cat $RUNDIR/tmp.err
		exit $status
	}
	echo "ok"
	SOMETHING_CHANGED=true
}

# fix wrong init sequence nubmer (S19 is ok, K21 not)

rm -f /etc/rc*.d/???postgresql
add_init_script 19 postgresql

# May 2015 fsync bug (cant' read default cert files -- snakeoil)
#
cd /var/lib/postgresql/$release/main
link=$(ls -l server.crt 2>/dev/null) || :
echo "$link" | grep -q "ssl-cert-snakeoil" && {
	echo "  fixing May 2015 (fsync) bug"
	rm -f server.crt server.key
	cp /etc/ssl/certs/ssl-cert-snakeoil.pem server.crt
	cp /etc/ssl/private/ssl-cert-snakeoil.key server.key
	chown postgres:postgres server.crt server.key
	chmod 640 server.crt server.key
	SOMETHING_CHANGED=true
}


$SOMETHING_CHANGED && {
	restart_service postgresql || exit $?
}

admin_user=`jtconf pgsql.admin_user`	|| exit_missing_define "pgsql.amin_user"
admin_pw=`jtconf pgsql.admin_pw`	|| exit_missing_define "pgsql.amin_pw"

echo "  setting pgsql admin password (user: $admin_user)"
echo "$admin_user:$admin_pw" | chpasswd
cd /tmp	# to avoid su command complains about not accessible cwd
su $admin_user -c "echo \"ALTER ROLE $admin_user PASSWORD '$admin_pw';\" | psql" || exit $?

exit 0
