#!/bin/bash -e

PATH=/bin:/usr/bin:/sbin:/usr/sbin
STOP_TIMEOUT=60

if [ -f /usr/bin/agraph-control  -a "$0" -ef /usr/bin/agraph-control ]; then
    rpminstall=t
fi

if [ `id -u` = 0 ]; then
    root=t
fi

function usage {
    cat <<EOF
Usage: $0 [ --config <path to config file> ] start|stop|force-stop|reload
EOF
    exit 1
}

function determine_lib_dir {
    local tmp

    if [ -L "$0" ]; then
	tmp=`readlink -f $0`
	libdir=`dirname $tmp`
    else 
	libdir=`dirname $0`
    fi
}

function guess_config_file {
    if [ "$rpminstall" -a "$root" ]; then
	configfile=/etc/agraph/agraph.cfg
    elif [ "$rpminstall" ]; then
	echo Cannot determine location of configuration file.  Please use --config
	exit 1
    else 
	determine_lib_dir
	configfile=$libdir/agraph.cfg
    fi
}

function locate_agraph_bin {
    for dir in "`dirname $0`" agraph .; do
	local bin="$dir/agraph"
	if [ -f "$bin" -a -x "$bin" ]; then
	    agraph_bin="$bin"
	    return
	fi
    done
    echo "Cannot locate the 'agraph' executable"
    exit 1
}

function setup_vars {
    if [ -z "$configfile" ]; then
	guess_config_file
    fi
    
    if [ ! -f "$configfile" ]; then
	echo "Cannot locate configuration file (tried $configfile)."
	exit 1
    fi
    
    # Sets $agraph_bin
    locate_agraph_bin
    
    RUNAS=`$agraph_bin --config $configfile --get-config-value RunAs`
    PIDFILE=`$agraph_bin --config $configfile --get-config-value PidFile`
    LOGDIR=`$agraph_bin --config $configfile --get-config-value LogDir`
    SETTINGSDIR=`$agraph_bin --config $configfile --get-config-value SettingsDirectory`
}

function ag_chown {
    # The trailing colon after $RUNAS is deliberate. See the man page
    # for chown if you want to know what it means.
    if [ "$root" ]; then
	chown --preserve-root -R $RUNAS: "$@"
    fi
}

function prep_dir {
    mkdir -p $1
    ag_chown $1
}


function prep_pid {
    local piddir=`dirname $PIDFILE`
    
    if [ ! -e $piddir ]; then
        # Since the directory in which PIDFILE resides might be shared
        # with other programs, we must not chown it if it already 
        # exits.
	prep_dir $piddir
    fi
    
    touch $PIDFILE
    ag_chown $PIDFILE
}    
    
function prep {
    if [ "$root" ] && ! id $RUNAS >/dev/null 2>&1; then
	cat <<EOF
RunAs user '$RUNAS' does not exist in the passwd database.  

Please run the AllegroGraph configuration script or adjust the RunAs
setting in $configfile

EOF
	return 1
    fi


    prep_pid
    for dir in $LOGDIR $SETTINGSDIR; do
	prep_dir $dir
    done
    
    for dir in `$agraph_bin --config $configfile --get-config-value Catalog-Dirs`; do
	prep_dir $dir
    done
    
    return 0
}


function start_agraph {
    setup_vars
    prep

    cmdline_pad="                                                                   "

    if $agraph_bin --config $configfile $AGCONTROL_EXTRA --pad "$cmdline_pad"; then
	# TODO: Wait a short while for the server to start responding
	return 0
    else
	return 1
    fi
}

function pid_exists {
    /bin/kill -0 $1 2>/dev/null
}

function agraphpid {
    if [ -r $PIDFILE ]; then
	cat $PIDFILE
    else
	return 1
    fi
}

function signal_agraph_common {
    setup_vars
    
    local msg="$1"
    local signal="$2"
    
    echo -n "$msg"

    if ! pid=`agraphpid`; then
	echo ": Not running"
	return 1
    fi
    
    echo -n " ($pid): "

    if ! pid_exists $pid; then
	echo "Not running"
	return 1
    fi
    
    /bin/kill -s $signal $pid
}

function stop_agraph {
    signal_agraph_common "Stopping agraph" TERM
    local res=$?
    if [ $res -ne 0 ]; then
	return $res
    fi
    echo -n "..."

    local cycles=$STOP_TIMEOUT
    while [ $cycles -gt 0 ]; do
        if pid_exists $pid; then
	    echo -n "."
            sleep 1
            cycles=$[ $cycles - 1 ]
        else
	    # Successful stop
	    echo "  Stopped"
	    rm -f $PIDFILE
	    return 0
        fi
    done

    echo
    echo "agraph ($pid) did not shutdown cleanly within $TIMEOUT seconds." >&2
    echo "Using $0 force-stop will force termination of agraph." >&2
    return 144
}

function force_stop_agraph {
    signal_agraph_common "Forcibly stopping agraph" QUIT
    local res=$?
    if [ $res -eq 0 ]; then
	echo "  Stopped"
    else
	return $res
    fi
}

function reload_agraph {
    signal_agraph_common "Reloading agraph configuration" USR1
    local res=$?
    if [ $res -eq 0 ]; then
	echo "Done"
    else
	return $res
    fi
}

case "$1" in
    --config)
	shift
	configfile="$1"
	shift
	if [ -z "$configfile" ]; then
	    usage
	fi
	;;
    -*)
	echo Unknown option: $1
	usage
	;;
esac

if [ $# -ne 1 ]; then
    usage
fi

control=$1

case "$control" in
    start)
	start_agraph
	;;
    force-stop)
        force_stop_agraph
        ;;
    stop)
	stop_agraph
	;;
    reload)
	reload_agraph
	;;
    *)
	usage
	;;
esac
