#!/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
# REQUIRE: LOGIN NETWORKING one-context-local
### 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"
desc="OpenNebula contextualization"
rcvar="${name}_enable"
start_precmd="${name}_prestart"
stop_cmd="${name}_stop"
command="/usr/sbin/one-contextd"
command_args="network"

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_prestart()
{
    if [ -f /var/run/one-context/context.sh.network ]; then
        warn "Service started once already."
        return 1
    fi
}

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

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

    echo '.'
}

load_rc_config $name
: ${one_context_enable:="yes"}
run_rc_command "$1"
