#!/bin/bash
# MythTV Remote for Zipit Z2
# See http://www.mythtv.org/wiki/Telnet_socket
# for keymapping options

# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

# Check for server and port
if [ -z ${1} ]; then
  echo "Usage: mythremote <SERVER> <PORT>"
  echo ""
  echo "Server can be ip address or name"
  echo "Default port is 6546 and is assumed if not given"
  exit 1
else
  SERVER=$1
fi
if [ -z $2 ]; then
  PORT=6546
else
  PORT=$2
fi

function getkey {
KEYPRESS=`dd if=/dev/input/event1 bs=16 count=1 2>/dev/null | od -x | grep -v 0000020`
#echo "HEX=$KEYPRESS"
#EVENT=`echo $KEYPRESS | sed 's/0000000.*0004 0004 //' | sed 's/ 0000//'`
echo $KEYPRESS > /tmp/event.tmp
EVENT=`cut -b 38-42 /tmp/event.tmp`
#echo "EVENT=$EVENT"
#EVENT=`cat /tmp/event.tmp`
rm /tmp/event.tmp
}

# Switch true/false in while loops to run testing loop
while false ; do
 getkey
 echo "HEX=$KEYPRESS"
 echo "EVENT=$EVENT"
done


while true ; do
getkey
# Now check if we should send command to myth
case $EVENT in
0008)
  # Up Arrow
  echo -e "key up\nexit\n" | netcat $SERVER $PORT 1>/dev/null
  ;;
0010)
  # Down Arrow
  echo -e "key down\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0018)
  # Left Arrow
  echo -e "key left\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0020)
  # Right Arrow
  echo -e "key right\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0028)
  # Center (aka enter)
  echo -e "key enter\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0029)
  # Enter
  echo -e "key enter\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0004)
  # Esc
  echo -e "key escape\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0007)
  # Play
  echo -e "play speed normal\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0006)
  # Stop
  echo -e "play stop\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0002)
  # Prev
  echo -e "play channel down\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0003)
  # Next
  echo -e "play channel up\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0005)
  # Zipit - TV
  echo -e "jump livetvinguide\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0001)
  # Home (Main Menu)
  echo -e "jump mainmenu\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
000a)
  # W (Weather)
  echo -e "jump mythweather\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
002d)
  # Spacebar (Pause)
  echo -e "play speed pause\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
001e)
  # Backspace
  echo -e "key w\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0030)
  # Volume Up
  echo -e "key ]\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
0031)
  # Volume Down
  echo -e "key [\nexit\n " | netcat $SERVER $PORT 1>/dev/null
  ;;
esac
done
