#!/bin/bash
#
# Simple script that changes the channels.conf for kids with a pass code via commands.conf
#
# Name: code.sh

######################################################################
#
#   vdr config directory, eg: [/usr/local/vdr]
#   |
#   +- kids
#   |   |-- code.sh
#   |   |-- commands.root.conf
#   |   |-- channels.root.conf
#   |   |-- commands.user.conf
#   |   |-- channels.kids.conf
#   |   |-- channels.user.conf
#   -   -
#
######################################################################
#
#   [commands.root.conf, commands.conf] entries:
#
#   Change channels for Kids : /usr/local/vdr/kids/code.sh change_kids
#   Change channels for User : /usr/local/vdr/kids/code.sh change_user
#
######################################################################
#
#   [commands.user.conf] entries:
#
#   [1] ->    : /usr/local/vdr/kids/code.sh 1
#   [2] ->    : /usr/local/vdr/kids/code.sh 2
#   [3] ->    : /usr/local/vdr/kids/code.sh 3
#   [4] ->    : /usr/local/vdr/kids/code.sh 4
#   [5] ->    : /usr/local/vdr/kids/code.sh 5
#   [6] ->    : /usr/local/vdr/kids/code.sh 6
#   [7] ->    : /usr/local/vdr/kids/code.sh 7
#   [8] ->    : /usr/local/vdr/kids/code.sh 8
#   [9] ->    : /usr/local/vdr/kids/code.sh 9
#   [0] ->    : /usr/local/vdr/kids/code.sh 0
#
######################################################################

## simpe code, only [0-9], e.g:
CODE_CMD="0123456789"

## vdr config directory, e.g:
CNFDIR=/usr/local/vdr

## kids directory, e.g:
MYPATH=/usr/local/vdr/kids

## runvdr, e.g:
RUNVDR=/usr/local/src/VDR/runvdr

## tempfile, e.g:
CM_CODE=${MYPATH}/code

CM_ROOT=${MYPATH}/commands.root.conf
CH_ROOT=${MYPATH}/channels.root.conf
CM_USER=${MYPATH}/commands.user.conf
CH_KIDS=${MYPATH}/channels.kids.conf
CH_USER=${MYPATH}/channels.user.conf

for x in ${CM_ROOT} ${CH_ROOT} ${CM_USER} ${CH_KIDS} ${CH_USER} ${RUNVDR}
do
	if [ ! -e "$x" ]
	then
		echo "Sorry can not change, this file not found: $(echo $x | sed -e '1,$s/[^\/]*\///g'), abort."

		exit 0
	fi
done

VAR=${CODE_CMD##*[^0-9,' ',-]*}

if [ ! -n "$VAR" ]
then
	echo "Sorry bad 'Access-Code' only [0-9], edit your change.sh (head), abort."

	exit 0
fi

function cmd ()
{
	echo "clear; killall -9 vdr; killall -9 runvdr; ${RUNVDR}" | at now
}

case "$1" in

   change_kids)
		cat ${CH_KIDS} >${CNFDIR}/channels.conf
		cat ${CM_USER} >${CNFDIR}/commands.conf

		cmd
	;;

   change_user)
		cat ${CH_USER} >${CNFDIR}/channels.conf
		cat ${CM_USER} >${CNFDIR}/commands.conf

		cmd
	;;

             *)

		echo -n $1 >>${CM_CODE}

		if [ "${CODE_CMD}" = "$(cat ${CM_CODE})" ]
		then
			cat ${CH_ROOT} >${CNFDIR}/channels.conf
			cat ${CM_ROOT} >${CNFDIR}/commands.conf

			rm ${CM_CODE}

			cmd

		elif [ "$(cat ${CM_CODE} | wc -m)" = "$(echo ${CODE_CMD} | wc -m)" ]
		then
			echo "Error 'Access-Code' abort."

			rm ${CM_CODE}
		else
			echo "Code: $(cat ${CM_CODE})"
		fi
	;;

esac