#!/bin/sh 
#
# requires at least cego version 2.49.16
# 
# $FreeBSD: ports/databases/cego/files/cego.in,v 1.2 2011/05/15 02:49:04 dougb Exp $
#

# PROVIDE: cego
# REQUIRE: LOGIN cleanvar
# KEYWORD: shutdown

#
# Add the following lines to /etc/rc.conf to enable cego:
# cego_enable (bool):      Set to "NO" by default.
#                          Set it to "YES" to enable cego
# cego_profiles (str):     Set to "" by default.
#                          Define your profiles here.
# cego_tablespc (str):     Set it to the tablespace
# cego_flags (str):        Set to "" by default.
#                          Extra flags passed to start command.

. /etc/rc.subr

name="cego"
rcvar=`set_rcvar`

command="/usr/local/bin/cego"

: ${cego_enable="NO"}
: ${cego_cpdump="NO"}
: ${cego_cleanup="NO"}
: ${cego_fsync="NO"}
: ${cego_conf="/usr/local/cego"}
: ${cego_root="/usr/local/cego"}
: ${cego_user="cego"}
: ${cego_numdbthread="30"}
: ${cego_poolsize="3x1000"}
: ${cego_protocol="fastserial"}
: ${cego_probeenabled="NO"}
: ${cego_probehost="localhost"}
: ${cego_probehost="2000"}
: ${cego_probeuser="cgadm/cgadm"}
: ${cego_probetimeout="30"}
: ${cego_lockexpire="0"}

flags="--mode=daemon"

start_cmd="cego_start"
stop_cmd="cego_stop"  
status_cmd="cego_status"  

cegoprog=/usr/local/bin/cego
cgadm=/usr/local/bin/cgadm

cego_start()
{
    echo "Starting cego database ${profile} ..."
    cd /usr/local/cego
    echo $cegoprog $command_args
    /usr/local/bin/sudo -u $cego_user $cegoprog $command_args

    if [ "${cego_probeenabled}" = "YES" ]; then

	# give a little time to start up daemon to be ready to connect
	sleep 2
	
	STARTTIME=`date '+%s'`

	doWait=yes

	while [ $doWait == "yes" ]
	do

            ${cgadm} --server=${cego_probehost} --port=${cego_probeport} --user=${cego_probeuser} --raw --cmd="list tableset" > /tmp/ts.out
            if [ $? == 0 ]
            then
		
                doWait=no
		
                for TSSTAT in `cat /tmp/ts.out`                                                                                                  
                do
		    	       
		    CURTS=`echo $TSSTAT | awk -F, '{ print $1 }'`
		    CURSTAT=`echo $TSSTAT | awk -F, '{ print $2 }'`
		    
		    tslist=$(echo ${cego_tablespc} | tr "," "\n")
		    for ts in $tslist
		    do
			if [ $ts == $CURTS ]
			then
			    # if tableset state not online, do wait
			    if [ $CURSTAT != "ONLINE" ]
			    then
				doWait=yes
			    fi
			fi
		    done
		done
	    fi

	    if [ $doWait == "no" ]
            then
                echo "All configured tablesets online"
            else 

		# check timeout
		
		CURRENTTIME=`date '+%s'`
		DELAY=`expr $CURRENTTIME - $STARTTIME`
		
		if [ "${DELAY}" -gt "${cego_probetimeout}" ]  
		then     
                    echo "Timeout occured during tableset awaiting online"
                    doWait=no
		fi
	    fi
	    
	    if [ $doWait == "yes" ]
	    then
		# wait 3 seconds before performing next online check
		sleep 3
	    fi
	done	
    fi

}

cego_stop()      
{
    echo "Stopping cego database ${profile} ..."
    cgpid=`cat ${cego_root}/${profile}.pid`
    /bin/echo -n " * Signaling PID:${myPID} ... "
    kill -INT ${cgpid} || { echo "Failed to signal PID:${cgpid}."; exit 1; }
    echo "Done."
    echo " * Waiting for lockfile to clear ..."
    echo '   This takes a few seconds. Please be patient!'
    myTimeout=1;
    while test -e ${cego_root}/${profile}.lck
    do
	test ${myTimeout} -ge 60 && { echo "Timeout reached. Exiting."; echo "This is NOT good."; exit 1; }
	sleep 1
	myTimeout=`expr ${myTimeout} + 1`;
    done
    echo "   Lockfile cleared in ${myTimeout} seconds."
    echo "Database shutdown complete." 
    echo ""
}

cego_status()
{
    if test -e ${cego_root}/${profile}.lck
    then
	echo "cego is up and running"
    else
	echo "cego is not running"
    fi
}

load_rc_config $name

if [ -n "$2" ]; then
        profile="$2"
        if [ "x${cego_profiles}" != "x" ]; then

		eval cego_tablespc="\${cego_${profile}_tablespc:-}"
                if [ "x${cego_tablespc}" = "x" ]; then
                        err 1 "You must define a tableset for db instance cego_${profile}_tablespc"
                fi

                eval cego_conf="\${cego_${profile}_conf:-${cego_conf}}"
                eval cego_root="\${cego_${profile}_root:-${cego_root}}"
		eval cego_user="\${cego_${profile}_user:-${cego_user}}"
		eval cego_numdbthread="\${cego_${profile}_numdbthread:-${cego_numdbthread}}"

		eval cego_poolsize="\${cego_${profile}_poolsize:-${cego_poolsize}}"

		eval cego_probeenabled="\${cego_${profile}_probeenabled:-${cego_probeenabled}}"
		eval cego_probehost="\${cego_${profile}_probehost:-${cego_probehost}}"
		eval cego_probeport="\${cego_${profile}_probeport:-${cego_probeport}}"
		eval cego_probeuser="\${cego_${profile}_probeuser:-${cego_probeuser}}"
		eval cego_probetimeout="\${cego_${profile}_probetimeout:-${cego_probetimeout}}"
		eval cego_lockexpire="\${cego_${profile}_lockexpire:-${cego_lockexpire}}"
		
		eval cego_cleanup="\${cego_${profile}_cleanup:-${cego_cleanup}}"
                if [ "${cego_cleanup}" = "YES" ]; then
		    CLEANUPOPT="--cleanup"
		fi
		
		eval cego_fsync="\${cego_${profile}_fsync:-${cego_fsync}}"
                if [ "${cego_fsync}" = "YES" ]; then
		    FSYNCOPT="--fsync"
		fi
		
		eval cego_cpdump="\${cego_${profile}_cpdump:-${cego_cpdump}}"
                if [ "${cego_cpdump}" = "YES" ]; then
		    CPDUMPOPT="--cpdump"
		fi
	      
                required_files="${cego_conf}/${profile}.xml"
                eval cego_enable="\${cego_${profile}_enable:-${cego_enable}}"
                command_args="--mode=daemon --dbxml=${required_files} --tableset=${cego_tablespc} --numdbthread=${cego_numdbthread} \
--poolsize=${cego_poolsize} --lockfile=${cego_root}/${profile}.lck --logfile=${cego_root}/${profile}.log --pidfile=${cego_root}/${profile}.pid --protocol=${cego_protocol} ${CLEANUPOPT} ${CPDUMPOPT} ${FSYNCOPT} --lockexpire=${cego_lockexpire}" 
                # echo "Setting command_args $command_args" 
        else
                warn "$0: extra argument ignored"
        fi
else
        if [ "x${cego_profiles}" != "x" -a "x$1" != "x" ]; then
                for profile in ${cego_profiles}; do
                        eval _enable="\${cego_${profile}_enable}"
                        case "x${_enable:-${cego_enable}}" in
                        x|x[Nn][Oo]|x[Nn][Oo][Nn][Ee])
                                continue
                                ;;
                        x[Yy][Ee][Ss])
                                ;;
                        *)
                                if test -z "$_enable"; then
                                        _var=cego_enable
                                else
                                        _var=cego_"${profile}"_enable
                                fi
                                warn "Bad value" \
                                    "'${_enable:-${cego_enable}}'" \
                                    "for ${_var}. " \
                                    "Profile ${profile} skipped."
                                continue
                                ;;
                        esac
                        echo "===> cego profile: ${profile}"
                        /usr/local/etc/rc.d/cego $1 ${profile}
                        retcode="$?"
                        if [ "0${retcode}" -ne 0 ]; then
                                failed="${profile} (${retcode}) ${failed:-}"
                        else
                                success="${profile} ${success:-}"
                        fi
                done
                exit 0
        fi
fi

cego_requirepidfile()
{
	if [ ! "0`check_pidfile ${cego_root}/${profile}.pid ${command}`" -gt 1 ]; then
		err 1 "${name} not running? (check $pidfile)."
	fi
}

run_rc_command "$1"
