#!/bin/sh

# usage function
function func_usage () {
  echo "Usage: VOB2Theora.sh <starttime> <endtime> <filename> <talkid>"
  echo "       starttime/endtime given as HH:MM:SS"
  echo "       filename          input file for conversion"
  echo "       talkid            provide talk id"
}

# convert from SMPTE to seconds
function func_convert2sec () {
  tspec=$1;
  tlen=${#tspec}   #strlen

  # parse seconds out of string
  tsecstart=$[ ${tlen} - 2 ]
  tsec=${tspec:$tsecstart:2} #substr

  # parse minutes
  tminstart=$[ ${tlen} - 5 ]
  if test $tminstart -ge 0; then
    tmin=${tspec:$tminstart:2} #substr
  else
    tmin=0
  fi

  # parse hours
  thrsstart=$[ ${tlen} - 8 ]
  if test $thrsstart -ge 0; then
    thrs=${tspec:$thrsstart:2} #substr
  else
    thrs=0
  fi

  # calculate number of seconds from hrs, min, sec
  tseconds=$[ $tsec + (($tmin + ($thrs * 60)) * 60) ]
}

# test number of parameters of script
if test $# -lt 3; then
  func_usage
  exit 0
fi

# convert start time
func_convert2sec $1
tstart=$tseconds

# convert end time
func_convert2sec $2
tstop=$tseconds

# input file
inputfile=$3
if test -e $inputfile; then
  echo "Converting $3 from $tstart sec to $tstop sec ..."
  echo ""
else
  echo "File $inputfile does not exist"
  exit 1;
fi

# talk id
talkid=$4

# convert using ffmpeg2theora
strdate=`date`;
strorga="LCA";
strcopy="LCA 2007";
strlicense="Creative Commons BY SA 2.5";
strcommand="ffmpeg2theora -s $tstart -e $tstop --date '$strdate' --organization '$strorga' --copyright '$strcopy' --license '$strlicense' --sync $inputfile -p preview -o $talkid.ogg"

echo $strcommand;

sh -c "$strcommand";
