#!/bin/bash

#
# Simple script that changes the $(channels|commands).conf for kids with a pass code via commands.conf
#

CODE_CMD=""

MYPATH=$(dirname $0)

if [ "${MYPATH}" = "." ]
then
	MYPATH=$(pwd)
fi

CM_CODE=${MYPATH}/code
CH_USER=${MYPATH}/channels.conf
CH_KIDS=${MYPATH}/channels.kids.conf
CM_USER=${MYPATH}/commands.conf
CM_KIDS=${MYPATH}/commands.kids.conf

for x in ${CM_KIDS} ${CH_KIDS} ${CM_USER} ${CH_USER}
do
	if [ ! -e $x ]
	then
		echo "Sorry can not change, this file not found:"
		echo
		echo "$x"

		exit 0
	fi
done

if [ "${CODE_CMD}" == "" ]
then
	echo "'Access-Code' not defined, edit your ${MYPATH}/change.sh (head)."

	exit 0
fi

function cmd ()
{
	echo "clear; killall -9 vdr; killall -9 runvdr; cd ${MYPATH}; ../../../VDR/runvdr" | at now
}

case "$1" in

     change)
		cat ${CH_KIDS} >${MYPATH}/../../channels.conf
		cat ${CM_KIDS} >${MYPATH}/../../commands.conf

		cmd
	;;

	run)
		if [ -e ${CM_CODE} ]
		then
			if [ ${CODE_CMD} -eq $(echo $(cat ${CM_CODE}) | sed -e 's/ //g') ]
			then
				cat ${CH_USER} >${MYPATH}/../../channels.conf
				cat ${CM_USER} >${MYPATH}/../../commands.conf

				rm ${CM_CODE}

				cmd
			else
				echo "Error 'Access-Code' abort."

				rm ${CM_CODE}
			fi
		else
			echo "Sorry 'Access-Code' not found."
		fi
	;;

       clean)
		if [ -e ${CM_CODE} ]
		then
			rm ${CM_CODE}

			echo "'Access-Code' cleaned up."
		else
			echo "Sorry 'Access-Code' not found."
		fi
	;;

       [0-9])
		echo $1 >>${CM_CODE}

		if [ -e ${CM_CODE} ]
		then
			echo "Code: $(echo $(cat ${CM_CODE}))"
		fi
esac
