#!/bin/bash
# start/stop script wrapper for postgresql via systemctl
#
# 2017-Jan-10 pmo  first version
#

test -z "$BASH" && exec /bin/bash $0 "$@"		# needed by Solaris: force bash

progname="${0##*/}"								# cut path
progname=${progname#rc}
progname=${progname#[KS][0-9][0-9]}
progname="${progname%%.*}"						# cut filetype

action="$1"										# save action
ec=0											# default: success
 ret_other=(success error)						# return values
ret_status=(running error dead_but_lock unused    unknown reserved5 not_configured)
 ret_start=(started error inv_args not_implemented insuff_privileges not_installed not_configured not_running)
  ret_stop=(stopped error inv_args not_implemented not_installed not_configured not_running)
rc_status () {									# inform user
    local s
    case "$action" in
	start)  s=${ret_start[$ec]};;
	stop)   s=${ret_stop[$ec]};;
	status) s=${ret_status[$ec]};;
        *)      test "$ec" = 0 && s=${ret_other[0]} || s=${ret_other[1]};;
    esac
    echo ": ${s:-(unknown exit code $ec)}"
}

# get actuall systemctl postgresql version
postgresql=$(systemctl list-unit-files | grep postgresql)
postgresql="${postgresql%%.service*}"

# check if enabled in systemctl
systemctl is-enabled $postgresql >/dev/null 2>&1 || {
    echo "      $progname: '$postgresql' not enabled in systemctl. Enabling now..."
    if systemctl --no-ask-password enable $postgresql 2>/dev/null; then
	echo "      $progname: '$postgresql' successfully enabled."
    else
	echo "      $progname: Could not enable '$postgresql' via 'systemctl enable $postgresql'."
	exit 1
    fi
}

# handle action
case "$action" in
    start)
        if test "$UID" -ne 0 && test "$(whoami)" != "postgres" ; then
            echo "      $progname: You must be root or postgres."; exit 1
        fi
    	echo -n "    Starting $progname"
	systemctl --no-ask-password start $postgresql; ec=$?
	rc_status
	;;
    stop)
        if test "$UID" -ne 0 && test "$(whoami)" != "postgres" ; then
            echo "      $progname: You must be root or postgres."; exit 1
        fi
    	echo -n "    Shutting down $progname"
	systemctl --no-ask-password stop $postgresql; ec=$?
    	rc_status
	;;
    restart)
	## Stop the service and regardless of whether it was
	## running or not, start it again.
        if test "$UID" -ne 0 && test "$(whoami)" != "postgres" ; then
            echo "     $progname: You must be root or postgres."; exit 1
        fi
	$0 stop; $0 start; ec=$?
	;;
    status)
    	echo -n "    Checking for $progname"
	systemctl is-active $postgresql >/dev/null; ec=$?
    	rc_status
	;;
    *)
	echo "Usage: $0 {start|stop|status|restart}"
	ec=1
	;;
esac
exit $ec

# Local Variables:
# mode:                 shell-script
# mode:                 font-lock
# comment-column:       56
# tab-width:            8
# End:
