#!/bin/bash
#
# Intel VCA Software Stack (VCASS)
#
# Copyright(c) 2018 Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# The full GNU General Public License is included in this distribution in
# the file called "COPYING".
#
# Intel VCA Scripts.
#

export EXESCRIPTDIR="/usr/lib/vca" # to avoid leading '/' in tar archive
export EXESCRIPT="vcanodeinfo.sh"
export VCACTRL="vcactl"
export CMD=""

stderr(){
	echo "*** $*" >&2
}

die(){
	local EXIT_CODE=$(( $? == 0 ? 99 : $? ))
	stderr "ERROR: $*"
	exit ${EXIT_CODE}
}

# Parse parameters passed to the script. All parameters used by vcanodeinfo.sh must
# be defined here, even if are not used by this script

function print_help {
	# Keep parameters alphabetically sorted in help and in the 'case' switch which parses them.
	# Prefer single-character options, i.e. do not introduce long options without an apparent reason.
	echo -e "Help:
	vcainfo [cardId [nodeId]] command [subcommand] [options]
	Commands:
		card-serial-nr					Read serial number
		load [subcommand]
			cpu [-loop] [-d <duration time in s>]	CPU usage
			gpu [-loop]				GPU usage
        Options:
        -d                              Set measurement duration for cpu usage
	-loop				Run script in loop
	Ex.: /usr/sbin/vcainfo 0 1 load cpu
	"
}

function isPositiveInt () {
        grep -Ecq '^[0-9]+$' <<< "$1"
}

parse_parameters () {
	[ $# == 0 ] || [ "$1" == "-h" ] || [ "$1" == "--help" ] && print_help && exit 0
	if isPositiveInt "$1"; then
		CARD_ID="$1"; shift
	else
		CARD_ID=$(vcactl status | sed -nre 's/.*Card: ([0-9]) Cpu: 0.*/\1/p')
	fi
	if isPositiveInt "$1"; then
                NODE_ID="$1"; shift
        else
		NODE_ID=(0 1 2)
        fi
	export CMD="$*"
}

run_script_on_node () {
	CARD_ADDR=$("$VCACTRL" network ip "$CARD_ID" "$1")
	(cd ${EXESCRIPTDIR} ;\
	        tar cf - $EXESCRIPT ) \
	        | ssh root@"$CARD_ADDR" 'export D=`mktemp -d`;
	        tar xf - -C $D;
	        chmod +x $D/'$EXESCRIPT';
	        $D/'"$EXESCRIPT $CMD"
}

parse_parameters "$@"
for nodeId in ${NODE_ID[*]}; do
	run_script_on_node "$nodeId"
done
