#!/bin/bash
#
# .---.                  .              .
# |                      |              |
# |--- .--. .-.  .-.  .-.|  .-. .--.--. |.-.  .-. .--.  .-.
# |    |   (.-' (.-' (   | (   )|  |  | |   )(   )|  | (.-'
# '    '     --'  --'  -' -  -' '  '   -' -'   -' '   -  --'
#
#                    Freedom in the Cloud
#
# Run tests on the system

# License
# =======
#
# Copyright (C) 2015-2016 Bob Mottram <bob@robotics.uk.to>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

PROJECT_NAME='freedombone'

export TEXTDOMAIN=${PROJECT_NAME}-tests
export TEXTDOMAINDIR="/usr/share/locale"

function show_help {
	echo ''
	echo $"${PROJECT_NAME}-tests"
	echo ''
	echo $'Runs tests on the system'
	echo ''
	echo $'     --help                   Show help'
	echo ''
	exit 0
}

function test_app_function_type {
	filename=$1
	fn_type=$2
	app_name=$(echo "${filename}" | awk -F '-app-' '{print $2}')
	app_function=$(cat "${filename}" | grep "function ${fn_type}_${app_name} {" | awk -F "${fn_type}_" '{print $2}' | awk -F ' ' '{print $1}')
	if [ ! ${app_function} ]; then
		echo $"Application ${app_name} does not contain a function called '${fn_type}_${app_name}'"
		echo ''
		echo "See ${filename}"
		exit 72852
	fi
}

function test_app_functions {
	if [ -f /usr/local/bin/${PROJECT_NAME} ]; then
		FILES=/usr/local/bin/${PROJECT_NAME}-app-*
	else
		FILES=/usr/bin/${PROJECT_NAME}-app-*
	fi

	# check that these functions exist
	interface_functions=( install remove backup_local backup_remote upgrade )

	# for all the app scripts
	for filename in $FILES
	do
		# for each expected interface function
		for f in "${interface_functions[@]}"
		do
			test_app_function_type ${filename} $f
		done
	done
}

while [[ $# > 1 ]]
do
	key="$1"

	case $key in
		-h|--help)
			show_help
			;;
		*)
			# unknown option
			;;
	esac
	shift
done

echo $'Running tests'

test_app_functions

echo $'All tests passed'

exit 0
