#!/bin/sh

ALBUM="${1}"

TRK1=$(ls ${ALBUM}*.mp3 | sort -g | head -1)
echo ${TRK1}

TALB=$(id3v2 -l ${TRK1} | grep ^TAL | awk -F':' '{print $2}' | awk '{$1=$1};1')

TPE1=$(id3v2 -l ${TRK1} | grep ^TPE1 | awk -F':' '{print $2}' | awk '{$1=$1};1')
if [ -z "${TPE1}" ]; then
    TPE1=$(id3v2 -l ${TRK1} | grep ^TP1 | awk -F':' '{print $2}' | awk '{$1=$1};1')
fi

TYER=$(id3v2 -l ${TRK1} | grep ^TYE | awk -F':' '{print $2}' | awk '{$1=$1};1')
if [ -z "${TYER}" ]; then
    TYER=$(id3v2 -l ${TRK1} | grep ^COMM | awk -F':' '{print $3}' | awk '{print $1}' | sed 's/^.//' | awk '{$1=$1};1')
fi

echo "TITLE=${TALB}" > "${ALBUM}.tags"
echo "ARTIST=${TPE1}" >> "${ALBUM}.tags"
echo "ALBUM=${TALB}" >> "${ALBUM}.tags"
echo "TRACKNUMBER=01" >> "${ALBUM}.tags"
echo "YEAR=${TYER}" >> "${ALBUM}.tags"

cat ${ALBUM}*.tags

ls ${ALBUM}*mp3 | sort -g | sed "s/^/file '/" | sed "s/$/'/" > "${ALBUM}.lst"
ffmpeg -f concat -i "${ALBUM}.lst" -vn -c:a flac -y "${ALBUM}.flac"
rm -f "${ALBUM}.lst"
metaflac --preserve-modtime --import-tags-from="${ALBUM}.tags" "${ALBUM}.flac"
oggenc "${ALBUM}.flac"
# cleanup
rm -f ${ALBUM}*.flac
rm -f ${ALBUM}*.mp3
rm -f ${ALBUM}*.jpg
rm -f ${ALBUM}*.tags


