#!/bin/bash

# Take an integer number of seconds and format it as hours:minutes:seconds
# Echoes result to stdout, so in order to use the output as a "return value",
# call the function like this:
#   RETURN_VALUE=$( format_time $NUM_SECONDS )
format_time ()
{
  let "HMS_HOURS=$1 / 3600"
  let "HMS_MINS=( $1 % 3600 ) / 60"
  let "HMS_SECS=$1 % 3600 % 60"

  [[ $HMS_HOURS -lt 10 ]] && HMS_HOURS="0${HMS_HOURS}"
  [[ $HMS_MINS -lt 10 ]] && HMS_MINS="0${HMS_MINS}"
  [[ $HMS_SECS -lt 10 ]] && HMS_SECS="0${HMS_SECS}"

  echo "${HMS_HOURS}:${HMS_MINS}:${HMS_SECS}"
}

# Take a string containing a time (like "02:15:25.3") and
# format it as an integer number of seconds. Fractional seconds
# are truncated. Result is echoed to stdout, so to use the output
# as a "return value", call the function like this:
#   RETURN_VALUE=$( unformat_time $TIME_STRING )
unformat_time ()
{
  HMS_HOURS=$( echo $1 | sed -r -e 's/0?([0-9]+):0?([0-9]+):0?([0-9]+)(\.[0-9])?/\1/' )
  HMS_MINS=$( echo $1 | sed -r -e 's/0?([0-9]+):0?([0-9]+):0?([0-9]+)(\.[0-9])?/\2/' )
  HMS_SECS=$( echo $1 | sed -r -e 's/0?([0-9]+):0?([0-9]+):0?([0-9]+)(\.[0-9])?/\3/' )
  let "TOT_SECONDS=$HMS_HOURS * 3600 + $HMS_MINS * 60 + $HMS_SECS"
  echo $TOT_SECONDS
}

# Retrieve the chapter breaks from the specified track on the DVD.
# Echoes a string to stdout with a list of chapter-start times
# (i.e., "0, 1:53, 15:26, 1:23:15" etc.)
# To use output as a "return value", call the function like this:
#   CHAPTER_START_TIMES=$( get_chapters $TITLE )
get_chapters ()
{
  CH_LIST=$( lsdvd -c -t $1 2>&1 | grep "Chapter:" | \
      sed -r -e 's/^.* Length: ([^,]+).*$/\1/' )
  
  # Assemble the list
  echo -n "0"
  TOTAL_SECS=0
  for CUR_CHAP in $CH_LIST; do
    CUR_SECS=$( unformat_time $CUR_CHAP )
    # Don't insert markers for 0-second chapters
    if [[ $CUR_SECS -gt 0 ]]; then
      let "TOTAL_SECS=$TOTAL_SECS + $CUR_SECS"
      CUR_TIME=$( format_time $TOTAL_SECS )
      echo -n ",$CUR_TIME"
    fi
  done
}

get_chapters "1"
