#!/bin/sh

# This script take a directory as first argument
# AND will try to :
#  * split the main flac file to several tracks with cue file
#  * tag flac tracks with cue data

flac_dir="${1}"

if [ ! -d "${flac_dir}" ]; then
	printf '%b' "Please give a directory as first argument."
	exit 1
fi

# Dependancies {{{
if ! command -v shnsplit > /dev/null; then
	printf '%b' "Please install shntool."
	exit 1
fi
if ! command -v cuetag > /dev/null; then
	printf '%b' "Please install cuetools."
	exit 1
fi
# }}}

# Go to the directory
cd "${flac_dir}" > /dev/null || exit 1

main_flac_file=$(ls -S1 *.flac | head --lines=1 --)
main_cue_file=$(ls -S1 *.cue | head --lines=1 --)

# Split main flac file
shnsplit -f "${main_cue_file}" -t %n.%t -o flac "${main_flac_file}"

# Rename pregap file
mv 00.pregap.flac pregap.flac

# Tag flac tracks
cuetag "${main_cue_file}" [0-9]*.flac

# Go back to the previous directory
cd - > /dev/null || exit 1

# Success
exit 0