#! /bin/bash
# start/stop script for censhare server
# compatible with Server-To-Server v2
#
# 2016-Sep-30 pmo  fixed CSS_ID read process
# 2016-Mar-08 pmo  removed pid dir handling because moved completely to censhare.rc
# 2015-May-19 pmo  corrected profile invocation to bash standard
# 2015-Feb-17 ahu  build version and build from properties files instead of file link
# 2014-Aug-28 pmo  read CSS_ID from ~CORPUS/.profile
# 2014-Jun-27 pmo  start stop status now also possible as non root user
# 2013-Nov-14 pmo  first cd before execute bin/censhare.rc
# 2012-Jul-04 pmo  fixed: set ulimit correct otherwise Error
# 2012-Mar-30 pmo  fixed: set correct id for solaris 11
# 2011-Jan-10 pmo  fixed: change rights for tmpfile to $COPRUS:$CORGRP
# 2010-Nov-04 mh   make censhare 4 compatible 
# 2010-Noc-02 ahu  changed write into tmpfile to be done as root in start/stop/status
# 2010-Okt-25 pl   add /etc as config script location for MacOSX
# 2010-Mar-16 pju  allow status check as corpus user
# 2009-Jul-07 pju  pass through censhare.rc exit state
# 2007-Aug-29 aka  vl: "id -g" needs /usr/xpg4/bin/id unter Solaris, MacOSX checked corrected
# 2007-Jul-31 aka  missing corpus home enabled (use of shared storage)
# 2007-Jul-10 aka  current cs2 "rewritten" to cs3
#
# pseudo comments for Novell/SuSE Linux
### BEGIN INIT INFO
# Provides: censhare
# Required-Start: $network sshd ora_censhare ora_lsnr
# Required-Stop: $network
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Description: Start the CenShare Service.
### END INIT INFO

# pseudo comments for RedHat / CentOS / Fedora Linux
### BEGIN
# chkconfig: 345 83 12
### END

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

progname=$(basename $0)
progname=${progname#rc}
progname=${progname#[KS][0-9][0-9]}

Error ()   { echo >&2 "$progname: $*"; exit 1; }

action="$1"                                             # save action
ec=0                                                    # default: success

# status handling a la LSB-2.x, -3.x
# http://refspecs.freestandards.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
 ret_other=(success error)                              # return values
ret_status=(running dead_but_run 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 insuff_privileges not_installed not_configured not_running)
#           0       1            2             3               4                 5             6              7
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}"
}

# read configuration
ConfErr () { echo >&2 "$progname: $*"; exit 6; }
cfglist=""						# collect tried pathes, output on error for debugging
ChkCfgfile () {						# first try /etc/sysconfig then /etc/s2s/sysconfig
    local cf="$1"; test -z "$cf" && ConfErr "$FUNCNAME(): filename missing."
    CONFIG_FILE=/etc/sysconfig/$cf;     cfglist="$cfglist $CONFIG_FILE"; test -r "$CONFIG_FILE" && return 0
    CONFIG_FILE=/etc/s2s/sysconfig/$cf; cfglist="$cfglist $CONFIG_FILE"; test -r "$CONFIG_FILE" && return 0
    CONFIG_FILE=/etc/$cf; cfglist="$cfglist $CONFIG_FILE"; test -r "$CONFIG_FILE" && return 0
    return 1						# failed
}
test -z "$CONFIG_FILE" && {				# if no config file defined by environment, look for
    ChkCfgfile $progname.$HOSTNAME || {			#     host specific one or
	ChkCfgfile $progname || {			#     general one or error
	    ConfErr "configuration missing, searched: '${cfglist# }'."; }; }
}							# endif
test -s "$CONFIG_FILE" && . $CONFIG_FILE		# read config
# check for mandatory config vars and set CSS_ID
test -z "$CORPUS" && ConfErr "corpus user CORPUS undefined."
test -z "$CSS_ID" && {
    eval test -r ~$CORPUS/.bash_profile && CSS_ID=$(eval grep CSS_ID ~$CORPUS/.bash_profile)
    test -z "$CSS_ID" && \
        eval test -r ~$CORPUS/.bash_login && CSS_ID=$(eval grep CSS_ID ~$CORPUS/.bash_login)
    test -z "$CSS_ID" && \
        eval test -r ~$CORPUS/.profile && CSS_ID=$(eval grep CSS_ID ~$CORPUS/.profile)
    CSS_ID=${CSS_ID##*CSS_ID=}
    CSS_ID=${CSS_ID%%\;*}
}

id=/usr/bin/id						# Linux, MacOSX/Darwin
test "$(uname)" = SunOS && id=/usr/xpg4/bin/id		# Solaris < 11
test "$(uname -r)" = "5.11" && id=/usr/bin/id		# Solaris 11

#CORPUS=corpus						# user, multiple instances may run under one user
CORGRP=$($id -g $CORPUS)				# group#
eval CORPUS_HOME=~$CORPUS
test -d $CORPUS_HOME || ConfErr "home dir '$CORPUS_HOME' missing, may not mounted."

# tempfile handling
tmpfile=${TMP:-/tmp}/$progname-$$.tmp
touch $tmpfile || Error "cannot touch '$tmpfile'."
chown $CORPUS:$CORGRP $tmpfile || Error "cannot chown '$CORPUS:$CORGRP' '$tmpfile'."
chmod 775 $tmpfile || Error "cannot chmod 755 '$tmpfile'."
OnExit () {
    set +x
    rm -f $tmpfile $tmpfile.*
}
trap OnExit EXIT

get_exitstate () {
    ec="$(cat $tmpfile 2>/dev/null)"
    case "$ec" in
        0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 ) ;;
        * ) ec=3 ;;
    esac
}

case "$1" in
    start | stop | restart )
        me=$(whoami)
        if test "$UID" -ne 0 && test "$me" != "$CORPUS" ; then
            echo "$progname: You must be root or $CORPUS."; exit 1
        fi
    ;;
    *) ;;
esac


case "$1" in
    start)
        me=$(whoami)
	echo -n "    Starting $progname"
	# set ulimit correct
	ulimit=16384
	test $(uname) == Darwin && ulimit=8192
	test $(ulimit -n) -lt $ulimit && ulimit -n $ulimit 2>/dev/null
	test $(ulimit -n) -lt $ulimit && Error "(cannot increase max open files: $(ulimit -n) - please incr to >=$ulimit)"
	# check and start only if not already running
        if test "$UID" -ne 0 && test "$me" != "$CORPUS" ; then
            echo "$progname: You must be root or $CORPUS."; exit 1
        fi
        if test "$UID" -eq 0; then
	    su - $CORPUS -c "if test -r .bash_profile; then . .bash_profile; elif test -r .bash_login; then . .bash_login; elif test -r .profile; then . .profile; fi; cd; bin/censhare.rc -i $CSS_ID $1 noframe; echo \$? >$tmpfile"
	elif test "$me" == "$CORPUS"; then
            if eval test -r ~$CORPUS/.bash_profile; then
                profile="~$CORPUS/.bash_profile"
            elif eval test -r ~$CORPUS/.bash_login; then
                profile="~$CORPUS/.bash_login"
            elif eval test -r ~$CORPUS/.profile; then
                profile="~$CORPUS/.profile"
            fi
	    eval source $profile
	    cd;  bin/censhare.rc -i $CSS_ID $1 noframe; echo $? >$tmpfile
	fi
        get_exitstate
	rc_status
	;;
    stop)
        me=$(whoami)
	echo -n "    Shutting down $progname"
	# check and stop only if already running
        if test "$UID" -ne 0 && test "$me" != "$CORPUS" ; then
            echo "$progname: You must be root or $CORPUS."; exit 1
        fi
	if test "$UID" -eq 0; then
	    su - $CORPUS -c "if test -r .bash_profile; then . .bash_profile; elif test -r .bash_login; then . .bash_login; elif test -r .profile; then . .profile; fi; cd; bin/censhare.rc -i $CSS_ID $1 noframe; echo \$? >$tmpfile"
	elif test "$me" == "$CORPUS"; then
	    cd;  bin/censhare.rc -i $CSS_ID $1 noframe; echo $? >$tmpfile
	fi
        get_exitstate
	rc_status
	;;
    restart)
	## Stop the service and regardless of whether it was
	## running or not, start it again.
	$0 stop; $0 start; ec=$?
	;;
    status)
        me=$(whoami)
        if test "$UID" -ne 0 && test "$me" != "$CORPUS" ; then
            echo "$progname: You must be root or $CORPUS."; exit 1
        fi
	test -e $CORPUS_HOME/[cC]en[sS]hare && {
            cssversion=$(sed -n "s|censhare.version=\([0-9]*.[0-9]*.[0-9]*\)|\1|p"  $CORPUS_HOME/css/build.common.properties)
            cssbuild=$(sed -n "s|build.number=\([0-9]*\)|\1|p"  $CORPUS_HOME/css/build.number)
            cs="censhare-Server-v$cssversion-b$cssbuild"
            echo -n "    Checking for $progname ($cs)"
            if test "$UID" -eq 0; then
                su - $CORPUS -c "if test -r .bash_profile; then . .bash_profile; elif test -r .bash_login; then . .bash_login; elif test -r .profile; then . .profile; fi; cd; bin/censhare.rc -i $CSS_ID $1 noframe; echo \$? >$tmpfile"
            elif test "$me" == "$CORPUS"; then
               cd;  bin/censhare.rc -i $CSS_ID $1 noframe; echo $? >$tmpfile
            fi
            get_exitstate
	} || {
	    echo -n "    Checking for $progname"; ec=3
	}
	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
# fill-column:		78
# End:
