#!/bin/bash
#
# Copyright (c) 2013-2017, Parallels International GmbH
#
# Our contact details: Parallels International GmbH, Vordergasse 59, 8200
# Schaffhausen, Switzerland.
#

CPUPOOLS_BIN=${CPUPOOLS_BIN:=/usr/sbin/cpupools}

function verify_caller {
	if [[ ! "$X_SHAMAN_CALLER" ]] ; then
		echo "The manual execution of this script is prohibited!" 1>&2
		echo "Please use vzmigrate or prlctl migrate for relocation purposes" 1>&2
		echo "and prlctl or vzctl for resource management." 1>&2
		exit 1
	fi
}

function handle_resource() {
	local handler_path="/usr/share/shaman"
	local handler_list=`find "${handler_path}" -mindepth 1 -maxdepth 1 -type d -printf "%f " | sort -r`
	local resource="${1}" handler_name="${2}" envs="${3}"
	local handler script cmd ret

	for handler in ${handler_list}; do
		if [ "X${resource#$handler}" != "X$resource" ]; then
			script=$handler_path/$handler/${handler_name}
			if [ -e "$script" ]; then
				cmd="${envs} $script"
				eval "$cmd"
				ret=$?
				if [ $ret -ne 0 ]; then
					echo "'$cmd' failed with code $ret" 1>&2
					return $ret
				fi
			fi
			return 0
		fi
	done
}

# Wait for service startup
# $1 - systemd service name
# $2 - timeout in seconds
# returns 0 on success, 1 - on timeout
function wait_service_start() {
	local name=$1
	local timeout=$2
	local delta=1
	local elapsed=0

	while [ $elapsed -le $timeout ]
	do
		status="$(/usr/bin/systemctl show --property=ActiveState $name)"
		[ "${status##ActiveState=}" == "active" ] && return 0
		sleep $delta
		let "elapsed += $delta"
	done
	return 1
}

