#!/bin/sh

set -e

CFGFILE=~/.freeboxremote
APIURL='http://hd1.freebox.fr/pub/remote_control'

function getcode()
{
    if ! [ -r $CFGFILE ]
    then
	echo "Vous n'avez pas encore entré le code de votre télécommande." >&2
	echo "Pour le faire, exécutez cette commande :" >&2
	echo "  $0 setcode <code>" >&2
	echo "Où <code> est le code à 6 chiffres donné par le boitier HD." >&2
	exit 1
    fi

    head -1 $CFGFILE
}

function checkarg()
{
    if [ -z "$2" ]
    then
	echo "Parmètre manquant pour $1."
	exit 2
    fi
}

function apicall()
{
    curl "${APIURL}?code=$(getcode)&key=$1$2"
}

cmd="$1"

case "$cmd" in
    ""|help)
	echo "Utilisation : $0 <commande> <arguments>"
	echo "Où commande peut être :"
	echo "   help                  affiche l'aide"
	echo "   keys                  affiche la liste des touches"
	echo "   setcode <code>        définit le code de la télécommande"
	echo "   getcode               affiche le code courant"
	echo "   press  <key>          appuie sur la touche"
	echo "   hold   <key>          appuie long sur la touche"
 	echo "   rep    <key> <n>      appuie n fois sur la touche"
        ;;
    setcode)
	checkarg "$cmd" "$2"
	echo $2 > $CFGFILE
	;;
    getcode)
	code=$(getcode)
	echo "Code actuel : $code"
	;;
    press)
	checkarg "$cmd" "$2"
	apicall $2
	;;
    hold)
	checkarg "$cmd" "$2"
	apicall $2 '&long=true'
	;;
    repeat|rep)
	checkarg "$cmd" "$2"
	checkarg "$cmd" "$3"
	apicall $2 "&repeat=$3"
	;;
    keys)
	cat <<EOF
       red

green       yellow

       blue

power   list   tv

1    2    3    info/epg
4    5    6    mail/media
7    8    9    help/options
back 0    swap pip

           up
vol_inc           prgm_inc
      left ok right 
vol_dec           prgm_dec
         down

mute     home     rec

bwd               fwd
      play  stop
prev              next

EOF
	;;
    *)
	echo "Commande non reconnue."
        ;;
esac



