#!/bin/bash

# usage function
function func_usage () {
  echo "Usage: VOB2Theora.sh <starttime> <endtime> <filename> <talkid> [artist [title] ]"
  echo "       starttime/endtime given as HH:MM:SS"
  echo "       filename          input file for conversion"
  echo "       talkid            provide talk id for output naming"
  echo "       artist            speaker or artist name"
  echo "       title             title of the talk"
}

# convert from SMPTE to seconds
function func_convert2sec () {
  tspec=$1;
  tlen=${#tspec}   #strlen
  
  # parse seconds out of string
  tsecstart=$[ ${tlen} - 2 ]
  tsecwidth=2
  if test "${tspec:$tsecstart:1}" = '0'; then
   tsecstart=$[ $tsecstart + 1 ]
   tsecwidth=1
  fi
  tsec=${tspec:$tsecstart:$tsecwidth} #substr
  echo "tsec $tsec"

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

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

  # 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

### set appropriate metadata for your event here ##
strdate="2007-01-09";
strloc="Sydney, Australia"
strcol="FOMS Position Statements"
strorga="FOMS";
strcopy="Copyright (C) 2007 Annodex Association";
strlicense="Creative Commons BY SA 2.5 http://creativecommons.org/licenses/by-sa/2.5/";

if test $# -gt 4; then
  strspeaker="--artist '$5'"
  strcopy="Copyright (C) 2007 $5" # speakers retain copyright
fi
if test $# -gt 5; then
  strtitle="--title '$6'"
fi

# convert using ffmpeg2theora
strcommand="ffmpeg2theora -s $tstart -e $tstop --date '$strdate' --location '$strloc' --organization '$strorga' --copyright '$strcopy' --license '$strlicense' $strspeaker $strtitle --sync $inputfile -p preview -o $talkid.ogg"

echo $strcommand;

sh -c "$strcommand";
