#!/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

buzzergpio="$(jq -r ".buzzer | .buzzergpio" < $configfile)"
strobegpio="$(jq -r ".buzzer | .strobegpio" < $configfile)"
swupgpio="$(jq -r ".swupgpio"  < $configfile)"
swdowngpio="$(jq -r ".buzzer | .swdowngpio" < $configfile)"

playerparam="$(jq -r ".playerparam" < $configfile)"
playerloop="$(jq -r ".buzzer | .playerloop" < $configfile)"

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

pollingtime="$(jq -r ".buzzer | .pollingtime" < $configfile)"
buzzertimeout="$(jq -r ".buzzer | .buzzertimeout" < $configfile)"
strobeduration="$(jq -r ".buzzer | .strobeduration" < $configfile)"

volumetimeout="$(jq -r ".buzzer | .volumetimeout" < $configfile)"
volumedelay="$(jq -r ".buzzer | .volumedelay" < $configfile)"
volumemax="$(jq -r ".buzzer | .volumemax" < $configfile)"

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

gpio mode $buzzergpio in

gpio mode $strobegpio out
gpio write $strobegpio 1

gpio mode $swdowngpio in
gpio mode $swupgpio in

volumevalue=0
amixer -q -c 2 sset 'Speaker' $volumevalue%

while true; do

	buzzerstat="$(gpio read $buzzergpio)"
	swupstat="$(gpio read $swupgpio)"
	swdownstat="$(gpio read $swdowngpio)"
	
	if [ "$buzzerstat" -eq 0 ] && [ "$swupstat" -eq 0 ]; then
		~/RandomVideo/RandomVideo.sh buzzer
		gpio write $strobegpio 0; sleep $strobeduration; gpio write $strobegpio 1 &
		sleep $buzzertimeout

	elif [ "$swupstat" -eq 1 ]; then

		if pgrep "$pgrepplayer" > /dev/null; then
               		pkill "$pgrepplayer"
		fi

		$playerfull $playerloop ~/RandomVideo/onair.mp4 &

		while [ "$swupstat" -eq 1 ]; do
			swupstat="$(gpio read $swupgpio)"
			sleep $pollingtime
		done

               	pkill "$pgrepplayer"

	elif [ "$volumevalue" -eq 0 ] && [ "$swdownstat" -eq 1 ]; then
		
		while [ "$volumevalue" -lt "$volumemax" ] && [ "$buzzerstat" -eq 1 ]; do
			volumevalue=$((volumevalue + 1))
			amixer -q -c 2 sset 'Speaker' $volumevalue%
			buzzerstat="$(gpio read $buzzergpio)"
			sleep $volumetimeout
		done
		
		sleep $volumedelay

	elif [ "$volumevalue" -gt 0 ] && [ "$swdownstat" -eq 0 ]; then

		while [ "$volumevalue" -gt 0 ] && [ "$swdownstat" -eq 0 ]; do
			volumevalue=$((volumevalue -1))
			amixer -q -c 2 sset 'Speaker' $volumevalue%
			swdownstat="$(gpio read $swdowngpio)"
			sleep $volumetimeout
		done

		sleep $volumedelay

	elif [ "$buzzerstat" -eq 1 ] && [ "$swupstat" -eq 0 ]; then
		sleep $pollingtime

	fi

done
