#!/bin/sh
#
#
#    Scalix Public License
#
#
#    The contents of this file are subject to the Scalix Public License
#    Version 1.1 ("License"); you may not use this file except in
#    compliance with the License. You may obtain a copy of the License at
#
# 
#    http://www.scalix.com/community/licensing 
#
# 
#    Software distributed under the License is distributed on an "AS IS"
#    basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
#    the License for the specific language governing rights and limitations
#    under the License.
#
# 
#    The Original Code is Scalix Server. 
#    The Initial Developer of the Original Code is Scalix Corporation. 
#    Copyright (C) 2006 Scalix Corporation. 
#    All Rights Reserved.
#    Additional Copyrights may apply - see the notice in each file
#
#
#
#
#
#
# chkconfig: 345 64 36
#
# description: Starts and stops the PostgreSQL backend daemon that handles \
#	       all database requests.
# processname: postmaster

# Modified for use in Scalix

# Version 6.5.3-2 Lamar Owen
# Added code to determine if PGDATA exists, whether it is current version
#     or not, and initdb if no PGDATA (initdb will not overwrite a database).

# Version 7.0 Lamar Owen
# Added logging code
# Changed PGDATA.

# Version 7.0.2 Trond Eivind Glomsrd <teg@redhat.com>
# use functions, add conditional restart
          
# Version 7.0.3 Lamar Owen <lamar@postgresql.org>
# Check for the existence of functions before blindly using them 
# in particular -- check for success () and failure () before using.
# More Cross-distribution support -- PGVERSION variable, and docdir checks.

# Version 7.1 Release Candidate Lamar Owen <lamar@postgresql.org>
# initdb parameters have changed.

# Version 7.1.2 Trond Eivind Glomsrd <teg@redhat.com>
# Specify shell for su
# Handle stop better - kill unwanted output, make it wait until the database is ready
# Handle locales slightly differently - always using "C" isn't a valid option 
# Kill output from database initialization 
# Mark messages for translation

# Version 7.1.2-2.PGDG Lamar Owen <lamar.owen@wgcr.org>
# sync up.
# Karl's fixes for some quoting issues.

# Version 7.2b2 Lamar Owen <lamar.owen@wgcr.org>
# version change.

# Version 7.2 final.  Lamar Owen <lamar.owen@wgcr.org>
# reload from Peter E.
# Eliminate the pidof postmaster test in stop -- we're using pg_ctl so we don't need pidof.
# Tested the $? return for the stop script -- it does in fact propagate.
# TODO: multiple postmasters.

# Version 7.3 Lamar Owen <lamar.owen@ramifordistat.net>
# Multiple postmasters, courtesy Karl DeBisschop

# Version 7.4 Lamar Owen.

# Version 7.4.3 Tom Lane <tgl@sss.pgh.pa.us>
# Support condstop for uninstall
# Minor other changes suggested by Fernando Nasser.

# Version 7.4.5 Tom Lane <tgl@sss.pgh.pa.us>
# Rewrite to start postmaster directly, rather than via pg_ctl; this avoids
# fooling the postmaster's stale-lockfile check by having too many
# postgres-owned processes laying about.

# Version 8.1 Devrim Gunduz <devrim@PostgreSQL.org>
#Increased sleep time from 1 sec to 2 sec.

# These will be set later.
PGVERSION=""
PGMAJORVERSION=""

# detect the distribution:
if [ -f /etc/redhat-release -o -f /etc/fedora-release ] ; then
    DISTRIBUTION="redhat"
elif [ -f /etc/SuSE-release ] ; then
    DISTRIBUTION="suse"
elif [ -f /etc/debian_version ] ; then
    DISTRIBUTION="debian"
else
    echo "Error: unsupported distribution" >&2
    exit 1
fi

# Source function library.
[ "$DISTRIBUTION" = "redhat" ] && . /etc/init.d/functions
[ "$DISTRIBUTION" = "suse" ] && . /etc/rc.status

if [ "$DISTRIBUTION" = "suse" ] ; then
    echo_success() {
        rc_status -v
    }
    echo_failure() {
        rc_status -v
    }
    success() {
        echo_success
    }
    failure() {
        echo_success
    }
elif [ "$DISTRIBUTION" = "debian" ] ; then
    echo_success() {
        echo ok
    }
    echo_failure() {
        echo failed
    }
    success() {
        echo_success
    }
    failure() {
        echo_success
    }
fi


# Get function listing for cross-distribution logic.
TYPESET=`typeset -f|grep "declare"`

# Get config.
[ -f /etc/sysconfig/network ] && . /etc/sysconfig/network

# Find the name of the script
NAME=`basename $0`
if [ ${NAME:0:1} = "S" -o ${NAME:0:1} = "K" ]
then
	NAME=${NAME:3}
fi

# For SELinux we need to use 'runuser' not 'su'
if [ -x /sbin/runuser ]
then
    SU="runuser -l"
else
    SU="su -"
fi

# Check that networking is up.
# Pretty much need it for postmaster.
[ "${NETWORKING}" = "no" ] && exit 0

if [ -n "$2" ] ; then
    ALL_INSTANCES="$2"
else
    ALL_INSTANCES=`/opt/scalix-postgres/bin/sxpsql-get-mounted-instances`
fi


script_result=0

start(){
	PSQL_START=$"Starting ${NAME} service ($SCALIX_INSTANCE): "

	# Make sure startup-time log file is valid
	if [ ! -e "$PGLOG" -a ! -h "$PGLOG" ]
	then
		touch "$PGLOG" || exit 1
		chown postgres:postgres "$PGLOG"
		chmod go-rwx "$PGLOG"
		[ -x /usr/bin/chcon ] && /usr/bin/chcon -t postgresql_log_t "$PGLOG" >/dev/null 2>&1
	fi

	# Check for the PGDATA structure
	if [ -f "$PGDATA/PG_VERSION" ] && [ -d "$PGDATA/base" ]
	then
		# Check version of existing PGDATA
		DATAVER=`cat "$PGDATA/PG_VERSION"`
		DATAPRIMARYVERSION=`echo "$DATAVER" | tr -d '[:alpha:]' | sed 's/^\([0-9]\{1,\}\).*/\1/'`
		PGPRIMARYVERSION=`echo "$PGVERSION" | tr -d '[:alpha:]' | sed 's/^\([0-9]\{1,\}\).*/\1/'`
		if [ ! -z "$DATAPRIMARYVERSION" ] && [ ! -z "$PGPRIMARYVERSION" ]
		then
			if [ $DATAPRIMARYVERSION -eq 7 ] && [ $PGPRIMARYVERSION -ge 8 ]
			then
				echo "Cannot start ${SCALIX_INSTANCE}.  Found a $DATAVER database but system is running PostgreSQL ${PGVERSION}." 1>&2
				script_result=1
				return
			fi
		fi
	else
		echo -n $"Initializing database: "
		if [ ! -e "$PGDATA" -a ! -h "$PGDATA" ]
		then
			mkdir -p "$PGDATA" || exit 1
			chown postgres:postgres "$PGDATA"
			chmod go-rwx "$PGDATA"
		fi
		# Clean up SELinux tagging for PGDATA
		[ -x /sbin/restorecon ] && /sbin/restorecon "$PGDATA"
		# Initialize the database
		$SU postgres -c "$PGENGINE/initdb --pgdata='$PGDATA' --auth='ident sameuser'" >> "$PGLOG" 2>&1 < /dev/null
		# Create directory for postmaster log
		mkdir "$PGDATA/pg_log"
		chown postgres:postgres "$PGDATA/pg_log"
		chmod go-rwx "$PGDATA/pg_log"

		[ -f "$PGDATA/PG_VERSION" ] && echo_success
		[ ! -f "$PGDATA/PG_VERSION" ] && echo_failure
		echo
 	fi

    if grep -q '^8\.' "$PGDATA/PG_VERSION" ; then
        extra_flags=""
    else
        extra_flags="-i"
    fi

	echo -n "$PSQL_START"
	$SU postgres -c "$PGENGINE/postmaster $extra_flags -h '$PGHOST' -p '$PGPORT' -D '$PGDATA' -k '$PGDATA' ${PGOPTS} &" >> "$PGLOG" 2>&1 < /dev/null
	sleep 2
	pid=`pidof -s "$PGENGINE/postmaster"`
	if [ $pid ] && [ -f "$PIDFILE" ]
	then
		success "$PSQL_START"
		echo
	else
		failure "$PSQL_START"
		echo
		script_result=1
	fi
}

stop(){
	echo -n $"Stopping ${NAME} service ($SCALIX_INSTANCE): "
	$SU postgres -c "$PGENGINE/pg_ctl stop -D '$PGDATA' -s -m fast" > /dev/null 2>&1 < /dev/null
	ret=$? 
	if [ $ret -eq 0 ]
	then
		echo_success
	else
		echo_failure
		script_result=0
	fi
	echo
}

restart(){
    stop
    start
}

reload(){
    $SU postgres -c "$PGENGINE/pg_ctl reload -D '$PGDATA' -s" > /dev/null 2>&1 < /dev/null
}
    
if [ "$DISTRIBUTION" = "debian" ] ; then
    status() {
        $SU postgres -c "$PGENGINE/pg_ctl status -D '$PGDATA'" > /dev/null 2>&1 < /dev/null
    }
fi

run_for_all_instances() {
    for SCALIX_INSTANCE in $ALL_INSTANCES ; do
        INST_DIR="$(/opt/scalix-postgres/bin/sxpsql-get-inst-dir $SCALIX_INSTANCE)"
        
        # Set defaults for configuration variables
        . /opt/scalix-postgres/bin/common-helpers.sh $SCALIX_INSTANCE

        if [ -z "$PGVERSION" ] || [ -z "$PGMAJORVERSION" ]
        then
                # PGVERSION is the full package version, e.g., 8.1.1
                # Note: the specfile ordinarily updates this during install
                PGVERSION=`$SU postgres -c "$PGENGINE/pg_ctl --version" | awk '{ print \$NF }'`
                # PGMAJORVERSION is major version, e.g., 8.0 (this should match PG_VERSION)
                PGMAJORVERSION=`echo "$PGVERSION" | sed 's/^\([0-9]*\.[0-9]*\).*$/\1/'`
        fi

	[ -f "$PGENGINE/postmaster" ] || exit 1

        PGPORT=$PSQL_PORT
        PGDATA=$PSQL_DIR
        PGLOG=$INST_DIR/pgstartup.log
        PIDFILE=$PGDATA/postmaster.pid

        export PGDATA
	export PGHOST
        export PGPORT
                
        # run the command:
        $*
    done
}

# This script is slightly unusual in that the name of the daemon (postmaster)
# is not the same as the name of the subsystem (postgresql)

[ "$DISTRIBUTION" = "suse" ] && rc_reset

# See how we were called.
case "$1" in
  start)
	run_for_all_instances start
	;;
  stop)
	run_for_all_instances stop
	;;
  status)
    if [ "$DISTRIBUTION" = "suse" ] ; then
      run_for_all_instances eval checkproc -p \$PIDFILE \$PGENGINE/postmaster
      rc_status -v
    else
      run_for_all_instances status postmaster
      script_result=$?
    fi
	;;
  restart)
    run_for_all_instances restart
	;;
  reload|force-reload)
	run_for_all_instances reload
	;;
  *)
	echo $"Usage: $0 {start|stop|status|restart|reload|force-reload}"
	exit 1
esac

[ "$DISTRIBUTION" = "suse" ] && rc_exit
exit $script_result
