#!/bin/sh

# Copyright (c) 2012 Igor Bogomazov <[email protected]>

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# revision 2012111800

# Usage:
#       split2flac.sh media_file.flac cue_sheet.cue

err() {
       echo "$@" >&2
       exit 1
}

media_file="$1"
test -n "$media_file" || err "media file is not specified"
cue_file="$2"
test -n "$cue_file" || err "CUE file is not specified"

test -n "$tmp" || tmp="$(mktemp -d --tmpdir=./ split2flac.XXXXXX)"
test -n "$tmp" || err "Temporary directory is not created"

convertMedia() {
       if mac "$media_file" -v ; then
               mac "$media_file" /dev/stdout -d \
                       | flac --best -c /dev/stdin >"$tmp"/out.flac
               return $?
       fi
       # assume it is FLAC by default
       ln "$media_file" "$tmp"/out.flac
}

test -e "$tmp"/out.flac \
       || convertMedia || err "Media file convertion failed"
flac -t "$tmp"/out.flac || err "FLAC file is corrupted: ""$tmp"/out.flac

splitMedia() {
       cuebreakpoints "$cue_file" \
               | shnsplit -d "$tmp" -O always -a track -o flac "$tmp"/out.flac
       return $?
}

splitMedia || err "Media file splitting failed"
cuetag "$cue_file" "$tmp"/track*flac || err "Setting tags failed"

renameMedia() {
       file="$1"
       cap_sed='^[[:space:]]*comment\[[[:digit:]]+\][[:space:]]*:[[:space:]]*([^[:space:]=][^=]*=.*)$'
       cap_title='TITLE'
       cap_tracknumber='TRACKNUMBER'
       name="$(
               metaflac --list --block-type=VORBIS_COMMENT "$file" \
                       | sed -nr 's@'"$cap_sed"'@\1@p' \
                       | awk -F= '
                               BEGIN {
                                       title = ""
                                       track = ""
                               }
                               (toupper($1) ~ "'"$cap_title"'") {
                                       title = $2
                               }
                               (toupper($1) ~ "'"$cap_tracknumber"'") {
                                       track = $2
                               }
                               END {
                                       if (track == "" || title == "") exit;
                                       printf "%02d. %s.flac", track, title
                               }
                       '
       )"
       test -n "$name" && mv "$file" "$name"
}

fails=
for file in "$tmp"/track*flac ; do
       if ! renameMedia "$file" ; then
               echo "Failed to compose name for: ""$file"
               fails=true
       fi
done

test -z "$fails" && {
       rm -f "$tmp"/out.flac
       rmdir "$tmp"
}

exit 0