#!/bin/bash
#
# Version: 0.2 (13.11.2014)
# Adrian (Sauron) Siemieniak
#
# This script will split FLAC or WAVE file into OGG files, performing also encoding, normalization, tagging and renaming those files
#
# Script requires shnsplit (from shntool), lltag, cuetag (from cuetools), vorbisgain, oggenc (from vorbis-tools) and flac
#
# On debian you can install all tools with: aptitude install shntool lltag cuetools vorbisgain vorbis-tools flac
#

if [ "$1" == "" ] || [ "$2" == "" ]; then
	echo "Usage: splitcueflac.sh file.cue file.flac|file.wav [oggquality]"
	exit
fi

FILE=$2
FILECUE=$1
OGGQ="7.5"

#
# Some preliminary tests
#
if [ "$3" != "" ]; then
	OGGQ="$3"
fi

if [ ! -f "$FILE" ]; then
	echo "FLAC or WAVE file does not exist!"
	exit
fi

if [ ! -f "$FILECUE" ]; then
	echo "CUE file does not exist!"
	exit
fi

TEMPDIR=`mktemp -d`
echo " Creating tmporary directory $TEMPDIR..."

cp -v "$FILECUE" "$FILE" "$TEMPDIR"

cd $TEMPDIR

FILEWAV="splitcue2ogg.wav"
if [ `file -b "$FILE" | grep -c "FLAC"` -eq 1 ]; then
	echo " Decoding FLAC to WAVE..."
	flac -d "$FILE" -o "$FILEWAV"
elif [ `file -b "$FILE" | grep -c "WAVE"` -eq 1 ]; then
	echo " We have the WAVE file already..."
	FILEWAV="$FILE"
else
	echo "File you want to split is not in FLAC or WAVE format!"
	rm -rf $TEMPDIR
	exit
fi

echo " Splitting WAV file..."
shnsplit -f "$FILECUE" "$FILEWAV"

echo " Encoding WAV to OGG..."
oggenc -q $OGGQ split-track*

echo " Applying CUE data do OGG TAGs..."
cuetag "$FILECUE" *.ogg

echo " Normalizing OGG files..."
vorbisgain *.ogg

echo " Renaming OGG files..."
lltag --yes --no-tagging --rename "%n_%t" *.ogg

echo " Copying back new OGG files..."
cd -
cp -v $TEMPDIR/*.ogg .

rm -vrf $TEMPDIR
