#!/bin/sh

ALBUM="${1}"

TRK1=$(ls ${ALBUM}*01.mp3)

TALB=$(id3v2 -l "${TRK1}" | grep ^TALB | awk -F':' '{print $2}' | awk '{$1=$1};1')
TPE1=$(id3v2 -l "${TRK1}" | grep ^TPE1 | awk -F':' '{print $2}' | awk '{$1=$1};1')
TYEAR=$(id3v2 -l ia_E_01.mp3 | grep ^COMM | awk -F':' '{print $3}' | awk '{$1=$1};1' | awk '{print $1}' | sed 's/^.//')

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

ls *mp3 | grep "${ALBUM}" | 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
