#!/bin/bash

# This file is part of Mkat
#
# Copyright (C) 2004, 2005 Dmitry Maksyoma <ledestin at amur.ru>.
#
# Mkat 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
# USA.

#1. burn audio CD from wav files
#2. rip the CD back and compare with the original wav files
#choose both or either of those

RCFILE=mkatrc 
[ -f /etc/$RCFILE ] && source /etc/$RCFILE
[ -z "$MKAT_LIBPATH" ] && \
  { echo >&2 "MKAT_LIBPATH not set (edit /etc/$RCFILE)"; exit 1; }
. "$MKAT_LIBPATH/helpers.sh" || exit 1
load_config /etc/$RCFILE
load_config ~/.$RCFILE

function usage {
  echo >&2 "missing arguments"
  echo "usage: $0 [-s] <wav file>..."
  echo "  -s		skip burn, only compare a CD with wav files"
  echo "  -h, --help    print this help"
  exit $1
}

case "$1" in
  "-h"|"--help") usage 0 ;;
  "-s") shift; SKIP_BURN=1 ;;
esac

[ $# -lt 1 ] && usage 1

set -e
if [ ! $SKIP_BURN ]; then
  echo "Burning audio CD..."
  cdrecord -v -dao -speed=4 "$@"
fi

echo "Ripping CD..."
[ -d "$TMP" ] || mkdir "$TMP"
TMP=`mktemp -p "$TMP" -d`
trap "rm -rf $TMP" EXIT
cd "$TMP" && cdparanoia -Bw
RIPPED_WAVS=(`ls -1`)

cd ~-
set +e
echo "Comparing ripped files with the original..."
PARAMS=("$@"); i=0; BROKEN_TRACK=0
while [ $# -gt $i ]; do
  cmp "${PARAMS[$i]}" "$TMP/${RIPPED_WAVS[$i]}"
  [ $? -eq 1 ] && BROKEN_TRACK=1
  i=$(($i+1))
done

if [ ! $BROKEN_TRACK ]; then
  echo "Catalog the CD..."
  mkata
fi
echo "Done..."
eject
