#!/bin/sh

# set OSVC_ROOT_PATH
test -f /etc/sysconfig/opensvc && . /etc/sysconfig/opensvc
test -f /etc/default/opensvc && . /etc/default/opensvc
test -f /etc/defaults/opensvc && . /etc/defaults/opensvc

if [ -z "$OSVC_ROOT_PATH" ]
then
	FLAG=/var/lib/opensvc/postinstall.restart
else
	FLAG=$OSVC_ROOT_PATH/var/postinstall.restart
	PATH=$PATH:$OSVC_ROOT_PATH/bin
	export PATH
fi

# create the flag hosting dir if it does not exist yet
mkdir -p `dirname $FLAG` >/dev/null 2>&1

# clean up lingering restart flag
rm -f $FLAG

# opensvc was not installed yet. just set the daemon start flag 
type nodemgr >/dev/null 2>&1 || {
        echo "adding opensvc daemon restart flag"
	touch $FLAG
	exit 0
}

nodemgr daemon running >/dev/null 2>&1
RUNNING=$?

# option not found => upgrade from 1.8-
if [ $RUNNING -eq 2 ]
then
	echo "daemon flagged for start"
	touch $FLAG

	echo "freeze all services"
	svcmgr freeze >/dev/null 2>&1
        # can output error if no services are present
	exit 0
fi

# set a flag for postinstall to know if the daemon should be restarted
if [ $RUNNING -eq 0 ]
then
	echo "daemon flagged for restart"
	touch $FLAG

        echo "stop the daemon, leaving the node in agent upgrade mode"
        OPENSVC_AGENT_UPGRADE=1 nodemgr daemon stop
fi
