#!/bin/bash
#
# Copyright Christophe Gros 2004-2005-2006 <skylendar@yahoo.com>
#
# The present script is relased under the General Public Licence.
#
# This script creates whatever is necessary (user, database, etc..) for the
# execution of skylendar 1.6.1

if [ -w $1/pg_hda.conf ]; then
	export PGDATA="$1"
elif [ -w /var/lib/pgsql/data/pg_hba.conf ]; then
	export PGDATA=/var/lib/pgsql/data
else
	echo pghba.conf not found ! Re-execute this present script with, as its argument, a path leading to the file pg_hba.conf
	exit 1
fi

HBA=$PGDATA/pg_hba.conf

function getcmd()
{
	if ! which $1 > /dev/null 2>&1; then
	echo $1 not found ! Check your postgres installation and system utilities.
	exit 1
	fi
}

function rel()
{
    su -c "pg_ctl reload -D $PGDATA" postgres > /dev/null 2>&1
}

if ! [ -w $HBA ]; then
echo $HBA doesn\'t seem to exist. Check whether postgres has been correctly installed or not
exit 1
fi

KP=`kde-config --prefix`
if [ -r $KP/share/apps/skylendar/installskydb.sql ]; then
	INSTPATH="$KP/share/apps/skylendar"
	INSTDB="$INSTPATH/installskydb.sql"
else
	echo Cannot install. Either KDE is not installed, or skylendar is missing.
	exit 1
fi

if ! [ -e /var/run/postmaster* ]; then
 if [ -x /etc/rc.d/init.d/postgresql ]; then
  echo Starting PostgreSQL
  /etc/rc.d/init.d/postgresql start
 else
  echo PostgreSQL doesn\'t seem to be present. Install it and run it with for example\: /etc/init.d/postgresql start
	exit 1
 fi
fi
 
if [ "$1" = "-d" ]; then
getcmd "psql"
getcmd "dropdb"
getcmd "dropuser"
getcmd "userdel"
getcmd "pg_ctl"

mv $HBA $HBA.tmp
echo "local all all trust" > $HBA
rel
su -c "echo \"drop group skyusers;\" | psql skylendar" postgres > /dev/null 2>&1
dropdb -U postgres skylendar > /dev/null 2>&1
dropuser -U postgres skylendar > /dev/null 2>&1
mv $HBA.tmp $HBA
rel
userdel "skylendar"
exit 0
fi

getcmd "psql"
getcmd "createuser"
getcmd "createdb"
getcmd "createlang"
getcmd "useradd"
getcmd "pg_ctl"
getcmd "kde-config"

if awk 'BEGIN { r = 0 }; /^skylendar/ { r = 1 }; END { exit r }' /etc/passwd; then
    echo created user skylendar
    useradd -r -g nogroup -d /tmp skylendar > /dev/null 2>&1
fi
mv $HBA $HBA.tmp
echo "local all all trust" > $HBA
rel
su -c "createuser -q -d -A -R skylendar" postgres > /dev/null 2>&1
su -c "createdb -E utf-8 skylendar"   skylendar > /dev/null 2>&1
su -c "createlang plpgsql skylendar"  postgres > /dev/null 2>&1
su -c "psql -f $INSTDB skylendar" skylendar > /dev/null 2>&1
mv $HBA.tmp $HBA
rel
