#!/bin/bash

#       Copyright (c) Stratus Technologies Bermuda Ltd., 2008.
#       All Rights Reserved. Unpublished rights reserved
#       under the copyright laws of the United States.
# 
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU Lesser General Public License as published
#       by the Free Software Foundation; version 2.1 only. with the special
#       exception on linking described in file LICENSE.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU Lesser General Public License for more details.

. /usr/libexec/xapi/cluster-stack/xhad/ha_rc

#
#   ha_set_pool_state    init | active | invalid [-C <config-file-name>]
#

#   Get new state
newstate=`param $*` || exit $?
shift

# get config-file name
cf=`getcf $*` || exit $?

status=$MTC_EXIT_SUCCESS

case $newstate in
    init)
        calldaemon pid > /dev/null
        status=$?
        case $status in
            $MTC_EXIT_DAEMON_IS_NOT_PRESENT)
                writestatefile setinit $cf
                status=$?
                ;;
            *)
                error "Could not set the pool state to INIT because the HA daemon may be present" "" $MTC_EXIT_DAEMON_IS_PRESENT
            ;;
        esac
        ;;
    active)
        calldaemon set_pool_state active
        status=$?

        if [ $status -ne $MTC_EXIT_SUCCESS ]; then
                writestatefile setactive $cf
                status=$?
        fi
        ;;
    invalid)
        calldaemon set_pool_state invalid
        status=$?

        if [ $status -ne $MTC_EXIT_SUCCESS ]; then
                writestatefile setinvalid $cf
                status=$?
        fi
        ;;
    *)
        error "Invalid new state $newstate" "" $MTC_EXIT_INVALID_PARAMETER
        ;;
esac

exit $status
