#!/bin/sh

# -------------------------------------------------------------------------- #
# Copyright 2002-2021, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

### BEGIN INIT INFO
# PROVIDE: one-context-force
# REQUIRE: one-context-local one-context
### END INIT INFO

. /etc/rc.subr

export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/root/bin

name="one_context_force"
desc="OpenNebula forced reconfiguration"
rcvar="${name}_enable"
start_precmd="${name}_prestart"
stop_cmd="${name}_stop"
status_cmd="${name}_status"
command="/usr/sbin/one-context-run"
command_args="force"

one_context_get_pids()
{
    # get main process PID and direct children processes
    for _pid in $(pgrep -f "${command} ${command_args}$"); do
        echo "${_pid}"
        pgrep -P "${_pid}"
    done
}

one_context_force_status()
{
    _pids=$(one_context_get_pids)

    if [ -z "${_pids}" ]; then
        echo "${name} is not running."
        return 1
    else
        echo "${name} is running as pids ${_pids}."
        return 0
    fi
}

one_context_force_prestart()
{
    if ! [ -f /var/run/one-context/context.sh.local ]; then
        warn "Service one-context-local must run first."
        return 1
    fi

    if ! [ -f /var/run/one-context/context.sh.network ]; then
        warn "Service one-context must run first."
        return 1
    fi

    _pids=$(one_context_get_pids)
    if [ -n "${_pids}" ]; then
        warn "${name} already running? (pids=${_pids})"
        return 1
    fi

    return 0
}

one_context_force_stop()
{
    echo -n "Stopping ${name}"

    _pids=$(one_context_get_pids)
    for _pid in $_pids; do
        kill -- "${_pid}" >/dev/null 2>&1
    done

    echo '.'
}

# run without any delay
export TIMEOUT=0

load_rc_config $name
: ${one_context_force_enable:="no"}
run_rc_command "$1"
