#!/bin/bash --
# -*- coding: UTF-8 -*-
# vim:set sw=4 softtabstop=4 ts=4 expandtab:
#
# dvd-to-mp3.sh - Creates a set of normalized mp3 files from a DVD.
# Originally used for TTC courses.  The script is meant to process DVDs
# with lectures, or speech.  It's not meant to be used to process music.
#
# (c) Maciej BliziƄski 2008
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
#
# Dependencies:
#   - MPlayer http://www.mplayerhq.hu/
#   - lame    http://lame.sourceforge.net/
#
# 2008-03-09 Version 0.1

# Logging functions. Those functions are identical to those from log4sh,
# but I don't want to have this dependency in this script.
function logger_debug { echo -n ; } # { echo >&2 "DEBUG $*"; }
function logger_info { echo >&2 "INFO $*"; }
function logger_warning { echo >&2 "WARNING $*"; }
function logger_error { echo >&2 "ERROR $*"; }

function enumerate_titles {
    local dvd_dev="$1"
    # It should handle both VIDEO_TS and video_ts.
    local video_ts="$(ls "${dvd_dev}" | grep -i video)"
    ls "${dvd_dev}/${video_ts}" | grep -i ^VTS | cut -d_ -f2 | sort | uniq
}

function usage {
    cat >&2 <<EOF
Usage: $0 [ options ]

Options:
    -h                      Display this message
    -d <dvd-device>         Path to DVD directory, can be /dev/dvd
                            or a directory on a hard disk with files
                            copied off a DVD.
    -a <name-of-the-dvd>    Save mp3 files in <name-of-the-dvd>
                            directory

Example:
    $0 -d "/media/My DVD Name" -a "This is this"
EOF
    exit "$1"
}

function do_title {
    logger_debug "do_title($*)"
    local dvd_dev="$1"
    local title="$2"
    local wav_file="${title}.wav"
    logger_info "Dumping title '${title}' to '${wav_file}'"
    mplayer \
        -really-quiet \
        -dvd-device "${dvd_dev}" \
        -vc null \
        -vo null \
        -ao pcm:waveheader:fast:file="${wav_file}" \
        -af volnorm=2:0.6 \
        "dvd://${title}"
    if [[ "$?" -ne 0 ]]
    then
        logger_error "mplayer returned an error."
        exit 1
    fi
    lame -m m -h -b 64 "${wav_file}" "${title}.mp3"
    rm -f "${wav_file}"
}

function main {
    logger_debug "main($*)"
    while getopts hd:a: optname
    do
        case ${optname} in
        h)
            usage 1
            ;;
        d)
            dvd_dev="${OPTARG}"
            ;;
        a)
            dvd_name="${OPTARG}"
            ;;
        esac
    done
    if [[ -z "${dvd_dev}" ]]
    then
        logger_error "DVD device name missing, please use option -d."
        usage 1
    fi
    if [[ -z "${dvd_name}" ]]
    then
        dvd_name="sound-from-dvd"
        logger_warning "Saving as '${dvd_name}'"
    fi

    if [[ -d "${dvd_name}" ]]
    then
        logger_error "${dvd_name} directory already exists."
        exit 1
    fi
    mkdir -p "${dvd_name}"

    pushd "${dvd_name}"

    # logger_debug "$(enumerate_titles "${dvd_dev}")"
    for title in $(enumerate_titles "${dvd_dev}")
    do
        do_title "${dvd_dev}" "${title}"
    done

    popd
}

main "$@"