#!/bin/sh
FILE="${1}"
AUD="$(echo ${FILE%.*})"
CDIR=$(echo "${PWD##*/}" | sed 's/_/ /g')

echo ${FILE} ${AUD} ${CDIR}

TALB=$(id3v2 -l "${FILE}" | grep ^TALB | awk -F':' '{print $2}' | awk '{$1=$1};1')
TPE1=$(id3v2 -l "${FILE}" | grep ^TPE1 | awk -F':' '{print $2}' | awk '{$1=$1};1')
TYER=$(id3v2 -l "${FILE}" | grep ^TYER | awk -F':' '{print $3}' | awk '{$1=$1};1' | awk '{print $1}' | sed 's/^.//')
TYER=$(id3v2 -l "${FILE}" | grep ^TYER | awk -F':' '{print $2}' | awk '{$1=$1};1')
TRCK=$(id3v2 -l "${FILE}" | grep ^TRCK | awk -F':' '{print $2}' | awk '{$1=$1};1')
TIT2=$(id3v2 -l "${FILE}" | grep ^TIT2 | awk -F':' '{print $2}' | awk '{$1=$1};1')

echo "TITLE=${TIT2}" > "${AUD}.tags"
echo "ARTIST=Watch Tower" >> "${AUD}.tags"
echo "ALBUMARTIST=Watch Tower" >> "${AUD}.tags"
echo "DISCNUMBER=01/01" >> "${AUD}.tags"
echo "ALBUM=${CDIR}" >> "${AUD}.tags"
echo "TRACKNUMBER=${TRCK}" >> "${AUD}.tags"
echo "YEAR=${TYER}" >> "${AUD}.tags"

ffmpeg -i "${FILE}" -map_metadata -1 -vn -c:a flac -y "${AUD}.flac"
metaflac --preserve-modtime --import-tags-from="${AUD}.tags" "${AUD}.flac"
oggenc "${AUD}.flac"

rm -f "${AUD}.flac"
