#!/bin/sh
# SPDX-License-Identifier: Unlicense

configfile="config.json"

if [ -z "$(command -v jq)" ]; then
	echo "Missing \"jq\"!"
	exit 1
fi

if [ -z "$(command -v gpio)" ]; then
        echo "Missing \"gpio\"!"
        echo "This is a part of WiringPi-Package."
        exit 1
fi

player="$(jq -r ".player" < $configfile)"
if [ -z "$(command -v $player)" ]; then
        echo "Missing \"$player\"!"
        exit 1
fi

if [ $# -eq 0 ]; then
        echo "Missing parameter!"
	exit 1
fi

if [ $# -gt 1 ]; then
	echo "To much parameters!"
	exit 1
fi

if [ "buzzer" != "$1" ] && [ "cron" != "$1" ]; then
	echo "parameters must be \"buzzer\" or \"cron\"!"
	exit 1
fi

swupstat="$(gpio read $swupgpio)"
if [ "$swupstat" -eq 1 ]; then
	exit 1
fi

folder="$(jq -r ".RandomVideo | .folder" < $configfile)"
playerparam="$(jq -r ".playerparam" < $configfile)"
pgrepplayer="$(jq -r ".pgrepplayer" < $configfile)"

swupgpio="$(jq -r ".swupgpio" < $configfile)"

playerfull="$(command -v $player) $playerparam"

if pgrep "$pgrepplayer" > /dev/null; then
	if [ "$1" = "buzzer" ]; then
		pkill "$pgrepplayer"
	
	elif [ "$1" = "cron" ]; then
		exit 1

	fi

else 
	$playerfull "$(find "$folder" -maxdepth 1 -type f |sort -R |head -n1)" &

fi
