#!/bin/bash
#
# Intel VCA Software Stack (VCASS)
#
# Copyright(c) 2015-2019 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.
#

exec 2> >( while read L ; do echo -e "$(date)\t${1##*/}\t${L}" ; done >>/var/log/vca/vca_auto_boot.log )

export PATH="$PATH:/sbin:/bin"

start()
{
	/usr/sbin/vcactld
}

stop()
{
	vcactl os-shutdown || :
	VCACTRLD_PID=$(pidof /usr/sbin/vcactld) || return
	kill -s SIGTERM $VCACTRLD_PID
}

scan_for_devices()
{
	VCACTRLD_PID=$(pidof -s /usr/sbin/vcactld)
	if [ -p /var/run/vcactld ] && [ -n "${VCACTRLD_PID}" ]
	then
		logger "[VCA] Daemon ready with pid ${VCACTRLD_PID}"
		kill -s SIGUSR2 $VCACTRLD_PID
	else
		logger "[VCA] Daemon not ready for scan for devices."
	fi
}

vop_reset()
{
	echo vca_reinit_dev ${1:0:1} ${1:1:2}  > /var/run/vcactld
}

# copy EPOCH values from files to modules, for every existing vca?? device
reload() {
	local _EPOCHFILE _DEVICE _DEVICEDIR
	local _CARDID _NODEID
	local _ERROR=0
	shopt -s nullglob
	for _DEVICE in /sys/class/vca/vca??/epoch ; do
		_CARDID="${_DEVICE: -8:1}"
		_NODEID="${_DEVICE: -7:1}"
		_EPOCHFILE="$( /usr/sbin/vcactl config-show "${_CARDID}" "${_NODEID}" epoch-file | awk -F"epoch-file: " 'END {print $2}' )"
		# An empty _EPOCHFILE path indicates no ESOH:
		if [ -z "${_EPOCHFILE}" ] ; then
			echo "" > "${_DEVICE}" || { logger -p user.warning "[VCA] Clearing EPOCH for cardid=${_CARDID}, nodeid=${_NODEID} failed" ; _ERROR=1; }
		else
			grep -v "^#" "${_EPOCHFILE}" > "${_DEVICE}" || { logger -p user.warning "[VCA] Setting EPOCH for cardid=${_CARDID}, nodeid=${_NODEID} failed"; _ERROR=1; }
		fi
	done
	[ "${_ERROR}" -ne 0 ] && logger -p user.error "[VCA] Updating EPOCH values failed for at leat one node"
	return "${_ERROR}"
}

case $1 in
	start)
		reload || exit
		start
		;;
	stop)
		stop
		;;
	scan)
		scan_for_devices
		;;
	recreate_vop_virtio_device)
		vop_reset $2
		;;
	reload)
		reload || exit
		;;
esac
