#!/bin/sh
# Copyright (c) SWsoft Inc.
# All rights reserved

show_help()
{
	cat <<EOF
Usage:
    pg_manage --start
        Start PostgreSQL server.
    pg_manage --stop
        Stop PostgreSQL server
    pg_manage --restart
        Restart PostgreSQL server.
    pg_manage --status
        Check PostgreSQL server status.
    pg_manage --check-installed
        Exit 0 if PostgreSQL is installed, 1 otherwise
    pg_manage --create-admin-login LOGIN
        Create user LOGIN with administrative privileges.
        The password must be stored in PSA_PASSWORD environment variable.
    pg_manage --drop-admin-login LOGIN
        Drop administrative user LOGIN.
    pg_manage --set-admin-password LOGIN
        Change password for administrative user LOGIN.
        The password must be stored in PSA_PASSWORD environment variable.
    pg_manage --help
        Show this message.
EOF
}

postmaster_run()
{
	PID=`ps axww | awk '$5 ~ "'postmaster'$" {print $1}'`

	if [ -z "$PID" ]; then
		# PG is not running
		return 1
	fi

	return 0
}

postmaster_start()
{
    if ! postmaster_run; then
       if [ -f "$rc_dir/postgresql-${pg_real_ver}" ]; then
           $rc_dir/postgresql-${pg_real_ver} start >/dev/null 2>&1
       else
           $rc_dir/postgresql start >/dev/null 2>&1
       fi

       sleep 3

       need_stop_postmaster="stop_after_work"

       if ! postmaster_run; then
           echo "Unable to start PostgreSQL."
           echo 1
           exit 1
       fi
    fi
}

postmaster_stop()
{
    if postmaster_run; then
       if [ -f "$rc_dir/postgresql-${pg_real_ver}" ]; then
           $rc_dir/postgresql-${pg_real_ver} stop >/dev/null 2>&1
       else
           $rc_dir/postgresql stop >/dev/null 2>&1
       fi

       if postmaster_run; then
           echo "Unable to stop PostgreSQL."
           echo 1
           exit 1
       fi
    fi
}

postmaster_check_installed()
{
	exec test -x $rc_dir/postgresql
}

psql_query()
{
	if ! $pg_bin_dir/psql -U postgres -d template1 -qtc "$@"; then
		echo "Error on query to PostgreSQL"
		echo 1
		setup_pg_hba_conf
		exit 1
	fi
}

setup_pg_hba_conf()
{
	local extra_rule

	# We add things at start, not at end, so that our rules have top priority
	echo >$pg_hba.tmp
	for extra_rule; do
		echo "$extra_rule #Added by Plesk" >>$pg_hba.tmp
	done
	echo "local samegroup all password #Added by Plesk" >>$pg_hba.tmp
	echo >>$pg_hba.tmp

	# Filter out anything added by Plesk earlier, as well as blank lines
	sed -e '/#Added by Plesk/d' -e '/^$/d' $pg_hba >>$pg_hba.tmp &&
	cat $pg_hba.tmp >$pg_hba &&
	chmod 644 $pg_hba &&
	rm -f $pg_hba.tmp

	if [ $? -gt 0 ]; then
		echo "Unable to rewrite $pg_hba"
		echo 1
		return 1
	fi

	if postmaster_run; then
		kill -HUP $PID
		sleep 1
	fi

	return 0
}

create_admin_login()
{
	# Note: "grep -q ." checks for non-empty lines in output
	local login password login_esc
	login=`echo "$1" | sed -e "s/'/''/g"`
	password=`echo "$2" | sed -e "s/'/''/g"`
	login_esc=`echo "$1" | sed -e 's/\(["\\]\)/\\\1/g'`
	if ! psql_query "select * from pg_group where groname='template1'" | grep -q .; then
		psql_query "create group template1"
	fi
	if psql_query "select * from pg_user where usename='$login'" | grep -q .; then
		psql_query "alter user \"$login_esc\" password '$password' createdb createuser"
	else
		psql_query "create user \"$login_esc\" password '$password' createdb createuser"
	fi
	psql_query "alter group template1 add user \"$login_esc\""
}

drop_admin_login()
{
	# Note: "grep -q ." checks for non-empty lines in output
	local login login_esc
	login=`echo "$1" | sed -e "s/'/''/g"`
	login_esc=`echo "$1" | sed -e 's/\(["\\]\)/\\\1/g'`
	if ! psql_query "select * from pg_group where groname='template1'" | grep -q .; then
		psql_query "create group template1"
	fi
	if [ "X$login" != "Xpostgres" ]; then
		if psql_query "select * from pg_user where usename='$login'" | grep -q .; then
			psql_query "update pg_database set datdba=(select usesysid from pg_shadow where usename='postgres') where datdba=(select usesysid from pg_shadow where usename='$login')"
			psql_query "drop user \"$login_esc\""
		fi
	else
		psql_query "alter group template1 drop user \"$login_esc\""
	fi
}

set_admin_password()
{
	# Note: "grep -q ." checks for non-empty lines in output
	local login password login_esc
	login=`echo "$1" | sed -e "s/'/''/g"`
	password=`echo "$2" | sed -e "s/'/''/g"`
	login_esc=`echo "$1" | sed -e 's/\(["\\]\)/\\\1/g'`
	if ! psql_query "select * from pg_group where groname='template1'" | grep -q .; then
		psql_query "create group template1"
	fi
	if ! psql_query "select * from pg_user where usename='$login'" | grep -q .; then
		psql_query "create user \"$login_esc\" password '$password' createdb createuser"
	else
		psql_query "alter user \"$login_esc\" password '$password'"
	fi
	psql_query "alter group template1 add user \"$login_esc\""
}

if [ "$PLESK_INSTALLER_DEBUG" = yes ]; then
	set -x
fi

export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin

if [ "0`id -u`" -ne 0 ]; then
	echo "This script must be run as root"
	echo 1
	exit 1
fi

config="/etc/psa/psa.conf"

if [ ! -f $config ]; then
	echo "Unable to open $config file."
	echo 3
	exit 3
fi

config_text=`sed -e '/^#/d' -e '/^$/d' $config | awk '{print $1"="$2}'`
eval $config_text

rc_dir=$PRODUCT_RC_D
if [ -z "$rc_dir" ]; then
	rc_dir=$PRODUCT_ROOT_D/rc.d
fi
rc_script=$rc_dir/postgresql

pg_bin_dir=$PGSQL_BIN_D

if [ ! -x "$pg_bin_dir/psql" ]; then
	echo "PostgreSQL is not installed."
	echo 3
	exit 3
fi


pg_real_ver="`$pg_bin_dir/psql --version | head -1 | awk '{print $3}' - | awk -F'.' '{print $1"."$2}' -`"
case "$pg_real_ver" in
		7.[34]|8.[01])
		;;
	*)
		echo "Unsupported version of PostgreSQL is installed."
		echo 3
		exit 3
			;;
esac

if [ "XFedoraCore" = "XUbuntu" ]; then
    case "$pg_real_ver" in 
       8.0|7.4)
          pg_data_dir=/etc/postgresql/$pg_real_ver/main
       ;;
       *)
          pg_data_dir=$PGSQL_DATA_D
       ;;
    esac 
else
    pg_data_dir=$PGSQL_DATA_D
fi

pg_hba="$pg_data_dir/pg_hba.conf"

case "$1" in
	--status)
		if postmaster_run; then
			echo "is running"
		else
			echo "is stopped"
		fi
		;;

	--start)
		postmaster_start
		;;

	--stop)
		postmaster_stop
		;;

	--restart)
		postmaster_stop
		postmaster_start
		;;

	--check-installed)
		postmaster_check_installed
		;;

	--create-admin-login)
		if [ -z "$2" ]; then
			show_help
			exit 1
		fi

		login=$2
		password=$PSA_PASSWORD

		if [ -z "$password" ]; then
			echo "Variable PSA_PASSWORD is undefined"
			echo 1
			exit 1
		fi

		postmaster_start
		setup_pg_hba_conf "local template1 postgres trust"
		create_admin_login "$login" "$password"
		setup_pg_hba_conf

		if [ ! -z "$need_stop_postmaster" ]; then
			postmaster_stop
		fi
		;;

	--drop-admin-login)
		if [ -z "$2" ]; then
			show_help
			exit 1
		fi

		login=$2

		postmaster_start
		setup_pg_hba_conf "local template1 postgres trust"
		drop_admin_login "$login"
		setup_pg_hba_conf

		if [ ! -z "$need_stop_postmaster" ]; then
			postmaster_stop
		fi
		;;

	--set-admin-password)
		if [ -z "$2" ]; then
			show_help
			exit 1
		fi

		login=$2
		password=$PSA_PASSWORD

		if [ -z "$password" ]; then
			echo "Variable PSA_PASSWORD is undefined"
			echo 1
			exit 1
		fi

		postmaster_start
		setup_pg_hba_conf "local template1 postgres trust"
		set_admin_password "$login" "$password"
		setup_pg_hba_conf

		if [ ! -z "$need_stop_postmaster" ]; then
			postmaster_stop
		fi
		;;

	--repair-db-groups)
		postmaster_start
		setup_pg_hba_conf "local template1 postgres trust"
		while read database; do
			group=`echo "$database" | sed -e "s/'/''/g"`
			group_esc=`echo "$database" | sed -e 's/\(["\\]\)/\\\1/g'`
			if ! psql_query "select * from pg_group where groname='$group'" | grep -q .; then
				psql_query "create group \"$group_esc\""
			fi
			rm -f "$pg_data_dir/usrs_$database"
		done
		setup_pg_hba_conf

		if [ ! -z "$need_stop_postmaster" ]; then
			postmaster_stop
		fi
		;;

	--repair-db-users)
		postmaster_start
		setup_pg_hba_conf "local template1 postgres trust"
		while read user database; do
			user_esc=`echo "$user" | sed -e 's/\(["\\]\)/\\\1/g'`
			group_esc=`echo "$database" | sed -e 's/\(["\\]\)/\\\1/g'`
			psql_query "alter group \"$group_esc\" add user \"$user_esc\""
		done
		setup_pg_hba_conf

		if [ ! -z "$need_stop_postmaster" ]; then
			postmaster_stop
		fi
		;;

	*)
		show_help
		exit 1
esac

echo 0
exit 0
