#!/usr/bin/env bash
ME="[makevcd]:"
. tovid-init 2>/dev/null ||
{ echo -e "===============================================================\n"
echo -e "'tovid-init' not found.  Was tovid improperly installed?"
echo -e "Or are you trying to run the script directly?"
echo -e "Please run makevcd as:\ntovid vcd OPTIONS"
exit 1 ; }

# makevcd
# Part of the tovid suite
# =======================
# A bash script for creating a VCD cue/bin set and burning it
# to a recordable CD.
#
# Project homepage: http://tovid.wikia.com
#
# Copyright (C) 2005-2010
#
# 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 2 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Or see:
#
#     http://www.gnu.org/licenses/gpl.txt

SCRIPTNAME=`cat << EOF
--------------------------------
tovid vcd
Create cue/bin files for a (S)VCD and burn them to a CD
Version $TOVID_VERSION
$TOVID_HOME_PAGE
--------------------------------
EOF`

USAGE=`cat << EOF
Usage: tovid vcd [OPTIONS] {VCDIMAGER.xml}

Where OPTIONS may be any of the following:

  -overwrite         Overwrite existing cue/bin image
  -burn              (default only make image)
  -device DEVICE     (default /dev/cdrw)
  -speed NUM         (default 12)
  -force             Add --force to cdrdao command (needed for short slides)

And:

  VCDIMAGER.xml is the name of a file containing a VCDImager XML
      description (For XML format, see http://www.vcdimager.org/).
      If you use(d) 'makexml' to create the XML file, you can use
      that as input here.

See the tovid manual page ('man tovid') for additional documentation.

EOF`

SEPARATOR="=========================================="

# Print script name, usage notes, and optional error message, then exit.
# Args: $1 == text string containing error message
usage_error ()
{
  echo "$USAGE"
  echo $SEPARATOR
  echo "$@"
  exit 1
}

# Print out a runtime error specified as an argument, and exit
runtime_error ()
{
    killsubprocs
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    echo "makevcd encountered an error during the VCD creation process:"
    echo $@
    echo "See if anything in the above output helps you diagnose the"
    echo "problem, and please file a bug report containing the above"
    echo "output to http://code.google.com/p/tovid/issues."
    echo "Sorry for the inconvenience!"
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    exit 1
}
# Defaults
QUIET=false
IMAGE=:
CDRW_DEVICE="/dev/cdrw"
BURN_SPEED=12
OVERWRITE=false
BURN=false

# ==========================================================
# EXECUTION BEGINS HERE
echo $"$SCRIPTNAME"

assert_dep "$vcd" "You are missing dependencies required to image and burn (S)VCDs!"

# check for valid CD burner.  This may fail but at least we tried
OIFS=$IFS \
IFS=$'\n' device=($(find -L /dev -type b -name 'cdrw*' 2>/dev/null )) IFS=$OIFS
CDRW_DEVICE=${device:-$CDRW_DEVICE}

while test x"${1:0:1}" = "x-"; do
    case "$1" in
      "-quiet" ) QUIET=: ;;
      "-overwrite" )
        OVERWRITE=:
        ;;
      "-burn" )
        BURN=:
        ;;
      "-device" )
        shift
        CDRW_DEVICE="$1"
        ;;
      "-speed" )
        shift
        BURN_SPEED=$1
        ;;
      "-force" )
        FORCE="--force"
        ;;
      * )
        usage_error "Error: Unrecognized command-line option $1"
        ;;
    esac

    # Get next argument
    shift
done

if test $# -ne 1; then
    usage_error "Please provide the name of a VCDimager XML file \
containing the (S)VCD description."
else
    # XML input is last argument
    VCDIMAGER_XML="$1"
fi

# Look for earlier attempts to image this VCD
for prev_try in "$VCDIMAGER_XML.cue" "$VCDIMAGER_XML.bin"; do
    if test -f "$prev_try"; then
        echo "Found a previous makevcd attempt: $prev_try!"
        if $OVERWRITE; then
            echo -n "Removing it...  "
            rm -fv "$prev_try"
        elif $BURN; then
            echo "Will use this for burning the disc."
            IMAGE=false
        else
            echo "Use '-overwrite' to override and re-image; or"
            echo "use '-burn' to write this existing image."
            echo "Exiting..."
            exit 1
        fi
    fi
done


# Create the cue/bin image
if $IMAGE; then
    # TODO: Warn if there isn't enough space to make cue/bin
    VCDIMAGER_CMD="vcdxbuild -c \"$VCDIMAGER_XML.cue\" -b \
        \"$VCDIMAGER_XML.bin\" \"$VCDIMAGER_XML\""
    echo $SEPARATOR
    echo "Creating cue/bin disc image with the following command:"
    echo $VCDIMAGER_CMD
    if eval $VCDIMAGER_CMD; then
        echo "Done."
        $QUIET || echo "Use 'tovid vcd -burn $VCDIMAGER_XML' to burn your VCD."
        $QUIET || echo "Thanks for using tovid!"
    else
        runtime_error "Imaging failed, please see vcdxbuild output above."
    fi
fi

# Burn the VCD
if $BURN; then
    # Sanity check: Make sure given device is valid (somehow)
    # before creating the cue/bin. Give option to proceed anyway?
    # (i.e., could there be any point to proceeding?)
    # Here's a simple way: just quit
    if test -b $CDRW_DEVICE; then :
       else
       echo "Couldn't find $CDRW_DEVICE! Stopping here."
       exit 1
    fi

    # Remind user to insert a CD
    $QUIET || echo "Please insert a blank CD-R(W) disc into your CD-recorder"
    $QUIET || echo "($CDRW_DEVICE) if you have not already done so."

    # check for cdrw and blank if so
    if cdrdao disk-info --device $CDRW_DEVICE --driver generic-mmc 2>&1 |
    grep -q CD-RW.*yes; then
    echo $SEPARATOR
    echo "Found rewritable CD - starting to blank in 10 seconds - press ctrl-c to quit"
    countdown 10
        cdrdao blank --driver generic-mmc  $CDRW_DEVICE
    fi
    # Burn the disc
    CDRDAO_CMD="cdrdao write --device $CDRW_DEVICE --driver generic-mmc \
        --speed $BURN_SPEED $FORCE \"$VCDIMAGER_XML.cue\""
    echo $SEPARATOR
    echo "Burning cue/bin image to $CDRW_DEVICE with the following command:"
    echo $CDRDAO_CMD
    if eval $CDRDAO_CMD; then
        if ! $QUIET; then
            echo "Done. You should now have a working VCD or SVCD. Please report"
            echo "any problems to http://code.google.com/p/tovid/issues."
            echo "Thanks for using tovid!"
        else
            echo "Done."
        fi
    else
        runtime_error "Could not burn the disc to $CDRW_DEVICE at speed $BURN_SPEED."
    fi
fi

exit 0
