#!/bin/bash
IFS=$(echo -en "\n\b")
cd "/Volumes/Media/EyeTV Archive"
for file in `find . -name "*.eyetv*" -maxdepth 1 | grep -v "Live TV Buffer" | grep -v "eyetvsched" | sed "s/.\///g"`
do
 echo "-----------------------------------------------------------------" >>  ~/eyetvexport.log
 cd "/Volumes/Media/EyeTV Archive/$file"
 echo "Processing $file....."
 echo "Processing $file....." >> ~/eyetvexport.log
 newfile=$(echo $file|sed 's/.eyetv//g')
 newfile=$(echo $newfile|cut -d',' -f1)
 if [ -f /Volumes/Media/TV/$newfile.mp4 ]
 then
  echo "File $newfile already exists, skipping conversion, doing rsync"
  echo "File $newfile already exists, skipping conversion, doing rsync" >> ~/eyetvexport.log
  rsync -avz --size-only /Volumes/Media/TV/$newfile.mp4 mosnas.mos-eisley.dk:/media/TV
 else
  echo "Processing $newfile"
  echo "Processing $newfile" >> ~/eyetvexport.log
  mpgfile=`ls | grep "mpg"`
  xmlfile=`ls | grep "eyetvr"`
  tnext=0
  for aline in `cat $xmlfile`
  do
   if [ $tnext -eq 1 ]
   then
    channel=$aline
   fi 
   tnext=`echo $aline | grep  "<key>channel name</key>" | wc -l`
  done
  channel=$(echo $channel|sed 's/<\/string>//g')
  channel=$(echo $channel|cut -d'>' -f2)
  echo "Channel $channel"
  echo "Channel $channel" >> ~/eyetvexport.log
  if [ $channel == 'TV 2 DK' ]
  then
   /Applications/VLC.app/Contents/MacOS/VLC -I dummy -vvv "/Volumes/Media/EyeTV Archive/$file/$mpgfile" --sub-track=3 --sout "#transcode{vcodec=h264,vb=2048,acodec=mpga,ab=256}:standard{mux=mp4,dst=\"/Volumes/Media/TV/${newfile}.mp4\",access=file,soverlay" --sout-transcode-soverlay vlc://quit
   echo "Using VLC for ${newfile}.mp4"
   echo "Using VLC for ${newfile}.mp4" >> ~/eyetvexport.log
  else
   if [ $channel == 'DR HD' ]
   then
    /Applications/VLC.app/Contents/MacOS/VLC -I dummy -vvv "/Volumes/Media/EyeTV Archive/$file/$mpgfile" --sub-track=3 --sout "#transcode{vcodec=h264,vb=2048,acodec=mpga,ab=256}:standard{mux=mp4,dst=\"/Volumes/Media/TV/${newfile}.mp4\",access=file,soverlay" --sout-transcode-soverlay vlc://quit
    echo "Using VLC for ${newfile}.mp4"
    echo "Using VLC for ${newfile}.mp4" >> ~/eyetvexport.log
   else
    /Applications/HandBrakeCLI -e x264 -x b-adapt=2:rc-lookahead=50 -w 720 -f mp4 -q 20 -b 192 -i "/Volumes/Media/EyeTV Archive/$file/$mpgfile" -o "/Volumes/Media/TV/$newfile ($channel).mp4"
    echo "Using Handbrake for ${newfile}.mp4"
    echo "Using Handbrake for ${newfile}.mp4" >> ~/eyetvexport.log
   fi
  fi
  if [ $? == 0 ]
  then
   echo "fff"
   #rm -rf "/Volumes/Media/EyeTV Archive/$file"
  fi
 fi
 rsync -avz --size-only /Volumes/Media/TV/$newfile.mp4 mosnas.mos-eisley.dk:/media/TV
done