#!/bin/bash
# Use next environment variables:
# NODE_LIST_FILE - path to the file containing the list of active nodes in the cluster
# RESOURCE_LIST_FILE - path to the file containing the list of resources of broken node with their priorities
# OUTPUT_FD - descriptor of output file
#
# Copyright (c) 2013-2017, Parallels International GmbH
# Copyright (c) 2017-2019 Virtuozzo International GmbH. All rights reserved.
#
# Our contact details: Virtuozzo International GmbH, Vordergasse 59, 8200
# Schaffhausen, Switzerland.
#

. /usr/share/shaman/functions

verify_caller

if [ -z "$NODE_LIST_FILE" ]; then
	echo "NODE_LIST_FILE environment variable undefined" 1>&2
	exit 1
fi

if [ -z "$RESOURCE_LIST_FILE" ]; then
	echo "RESOURCE_LIST_FILE environment variable undefined" 1>&2
	exit 1
fi

if [ -z "$OUTPUT_FD" ]; then
	echo "OUTPUT_FD environment variable undefined" 1>&2
	exit 1
fi

if [ -z "$SRC_NODE_ID" ]; then
	echo "SRC_NODE_ID environment variable undefined" 1>&2
	exit 1
fi

if [ ! -e "$NODE_LIST_FILE" ]; then
	echo "File $NODE_LIST_FILE does not exist" 1>&2
	exit 1
fi

if [ ! -e "$RESOURCE_LIST_FILE" ]; then
	echo "File $RESOURCE_LIST_FILE does not exist" 1>&2
	exit 1
fi

PDRS=/usr/libexec/pdrs-client

TMPFILE=`mktemp $RESOURCE_LIST_FILE.XXXXXXXX`
if [ -z "$TMPFILE" ]; then
	echo "mktemp error" 1>&2
	exit 1
fi
# the resource file contains the following records: name<newline>priority<newline>path<newline>
cat $RESOURCE_LIST_FILE | \
while ((1))
do
	read NAME
	[ -z "$NAME" ] && break
	read PRIO 
	if [ -z "$PRIO" ]; then
		echo "empty resource priority at $RESOURCE_LIST_FILE" 1>&2
		exit 1
	fi
	read RPATH
	if [ -z "$RPATH" ]; then
		echo "empty resource path at $RESOURCE_LIST_FILE" 1>&2
		exit 1
	fi
	ENV="RESOURCE_PATH=\"$RPATH\""
	# get resource type and max memory size for resource
	TYPE_MEM=$(handle_resource "$NAME" getparam "$ENV")
	if [ -n "$TYPE_MEM" ] ; then
		# save resource params for pdrs:
		# name<newline>priority<newline>max_mem_size<newline>
		echo "$NAME" >> $TMPFILE
		echo $PRIO >> $TMPFILE
		echo "$TYPE_MEM" >> $TMPFILE
	fi
done

# and call pdrs with available node list and resource list
$PDRS schedule $NODE_LIST_FILE $TMPFILE $SRC_NODE_ID >&$OUTPUT_FD
ret=$?
unlink $TMPFILE
exit $ret
