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

SHAMAN="/usr/sbin/shaman"
AWK="/bin/awk"

function verify_caller {
	if [[ ! "$X_SHAMAN_CALLER" ]] ; then
		echo "The manual execution of this script is prohibited!" 1>&2
		exit 1
	fi
}

# 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
}

# Wait for process is finished.
# $1 - process PID
# $2 - check file
# $tmo must be set before call. It is global to allow cumulative timeout.
# $WORK_DIR, $MIN_FREE_MB_DIR are global and optional.
function wait_timed() {
	local towait="$1"
	local watch="$2"
	local cnt=0

	while kill -0 "$towait" 2>/dev/null; do
	if [ "$tmo" -le 0 ]; then
		break;
	fi
	sleep 1
	tmo=$((tmo - 1))
	cnt=$((cnt + 1))
	if [ -n "$watch" ]; then
		if [ -f "$watch" ] && [ ! -s "$watch" ]; then
			if [ "$cnt" -ge 60 ]; then
				break;
			fi
		fi
	fi
	if [ -n "$WORK_DIR" ] && [ -n "$MIN_FREE_MB_DIR" ] &&
		[ "$(get_avail_mb "$WORK_DIR")" -le "$MIN_FREE_MB_DIR" ]; then
		break;
	fi
	done
}

# Returns free space on partition in megabytes.
# $1 - directory path
function get_avail_mb() {
    df -m --output=avail "$1" | "$AWK" 'NR==2'
}
