#!/bin/sh
DBUSER="mythtv"
DBPASSWORD="password"
DATABASE="mythconverg"

if [ $# -lt 6 ]
then
    echo Usage: channel_add.sh frequency netid tsid pid sourceid chan_num
    exit 1
fi
for num in $@
do
	if [ `echo $num | egrep -c '^[0-9]+$'` -eq 0 ]
	then
		echo Parameter Error
		exit 1
	fi
done

GET_MPLEXID="SELECT \`mplexid\` \
FROM \`dtv_multiplex\` \
WHERE \`sourceid\` =$5 \
AND \`transportid\` =$3 \
AND \`networkid\` =$2 \
AND \`frequency\` =$1"
SET_MPLEXID="INSERT INTO \`dtv_multiplex\` \
(\`sourceid\`, \`transportid\`, \`networkid\`, \`frequency\`,  \`symbolrate\` , \`polarity\` ) \
VALUES ('$5', '$3', '$2', '$1', '27500000', 'h');"

CHANID=`expr $5 \* 1000 + $6`
MPLEXID=`mysql -u $DBUSER -p$DBPASSWORD -e "$GET_MPLEXID" $DATABASE |tail -n1` 
if [ -z "$MPLEXID" ]
then 
	mysql -u $DBUSER -p$DBPASSWORD -e "$SET_MPLEXID" $DATABASE
	MPLEXID=`mysql -u $DBUSER -p$DBPASSWORD -e "$GET_MPLEXID" $DATABASE |tail -n1` 
fi

SET_CHANNEL="INSERT INTO \`channel\` \
( \`chanid\`, \`channum\`, \`sourceid\`, \`mplexid\`, \`serviceid\` ) \
VALUES ('$CHANID', '$6', '$5', '$MPLEXID', '$4' );"

mysql -u $DBUSER -p$DBPASSWORD -e "$SET_CHANNEL" $DATABASE
if [ $? -eq 0 ]
then
	echo "New channel added"
	exit 0
else
	echo "Channel add failed"
	exit 1
fi
