#!/bin/sh
# Script that parses the audio.cddb file and adds its tags to the
# flac metadata. Call from an album directory and use --dowrite to
# actually write the tags (otherwise the commands will just be written
# to stdout). Use --incremental to add tags, otherwise existing tags
# that will be written are removed first
#
# executables needed: grep, sed, tr, metaflac

cddbfile=audio.cddb

if [ ! -f $cddbfile ]; then
  echo "The current directory must contain a $cddbfile file"
  exit
fi

writemode=0
incmode=0
tagartist=""
tagalbum=""
taggenre=""
tagyear=""
tagperformer=""

error=0
while [ "$1" ]; do
  shft=1; found=0
  case "$1" in
    --artist) if [ "$tagartist" ]; then error=1; else tagartist="$2"; fi; found=1; shft=2;;
    --album) if [ "$tagalbum" ]; then error=1; else tagalbum="$2"; fi; found=1; shft=2;;
    --genre) if [ "$taggenre" ]; then error=1; else taggenre="$2"; fi; found=1; shft=2;;
    --year) if [ "$tagyear" ]; then error=1; else tagyear="$2"; fi; found=1; shft=2;;
    --performer) if [ "$tagperformer" ]; then error=1; else tagperformer="$2"; fi; found=1; shft=2;;
    --dowrite) writemode=1; found=1;;
    --incremental) incmode=1; found=1;;
  esac
  if [ $error -ne 0 ]; then
    echo "Error processing $1"
    exit
  fi
  shift $shft
done

#echo "WRITEMODE: $writemode"
#echo "ARTIST: <$tagartist>; ALBUM: <$tagalbum>; GENRE: <$taggenre>; YEAR: <$tagyear>"

dbartist=""
dbalbum=""
dbgenre=""
dbyear=""

result=`grep DTITLE= $cddbfile`
if [ "$result" ]; then
  result="${result#DTITLE=}"
  dbartist="${result%/*}"
  if [ "$dbartist" != "$result" ]; then
    dbartist=`echo $dbartist | sed -e 's/^[[:space:]]*\([^[:space:]]*\)[[:space:]]*$/\1/'`
    dbalbum="${result#*/}"
    dbalbum=`echo $dbalbum | sed -e 's/^[[:space:]]*\([^[:space:]]*\)[[:space:]]*$/\1/'`
  fi
fi

result=`grep DGENRE= $cddbfile`
if [ "$result" ]; then
  dbgenre="${result#DGENRE=}"
fi

result=`grep DYEAR= $cddbfile`
if [ "$result" ]; then
  dbyear="${result#DYEAR=}"
fi

#echo "DBARTIST: <$dbartist>; DBALBUM: <$dbalbum>; DBGENRE: <$dbgenre>; DBYEAR: <$dbyear>"

useartist="${tagartist}"
usealbum="${tagalbum}"
usegenre="${taggenre}"
useyear="${tagyear}"

if [ ! "$useartist" ];then
  if [ "$dbartist" ]; then
    useartist="$dbartist"
  else
    echo "Artist unknown and not specified, aborting"
    exit
  fi
fi

if [ ! "$usealbum" ]; then
  if [ "$dbalbum" ]; then
    usealbum="$dbalbum"
  fi
fi

if [ ! "$usegenre" ]; then
  if [ "$dbgenre" ]; then
    usegenre="$dbgenre"
  fi
fi

if [ ! "$useyear" ]; then
  if [ "$dbyear" ]; then
    useyear="$dbyear"
  fi
fi

valprotect=""
resettagswitch=""
if [ $writemode -eq 0 ]; then
  valprotect="\""
fi
if [ $incmode -eq 0 ]; then
  resettagswitch="--remove-tag=ARTIST --remove-tag=TITLE"
fi
artistswitch="--set-tag=ARTIST=${valprotect}${useartist}${valprotect}"
albumswitch=""
genreswitch=""
yearswitch=""
performerswitch=""
if [ "$usealbum" ]; then
  albumswitch="--set-tag=ALBUM=${valprotect}${usealbum}${valprotect}"
  if [ $incmode -eq 0 ]; then
    resettagswitch="$resettagswitch --remove-tag=ALBUM"
  fi
fi
if [ "$usegenre" ]; then
  genreswitch="--set-tag=GENRE=${valprotect}${usegenre}${valprotect}"
  if [ $incmode -eq 0 ]; then
    resettagswitch="$resettagswitch --remove-tag=GENRE"
  fi
fi
if [ "$useyear" ]; then
  yearswitch="--set-tag=DATE=${valprotect}${useyear}${valprotect}"
  if [ $incmode -eq 0 ]; then
    resettagswitch="$resettagswitch --remove-tag=DATE"
  fi
fi
if [ "$tagperformer" ]; then
  performerswitch="--set-tag=PERFORMER=${valprotect}${tagperformer}${valprotect}"
  if [ $incmode -eq 0 ]; then
    resettagswitch="$resettagswitch --remove-tag=PERFORMER"
  fi
fi

baseflags="--preserve-modtime"

#echo "$artistswitch $albumswitch $genreswitch $yearswitch"

tcount=0
numprocessed=0
while [ $tcount -lt 100 ]; do
  trackdesc="TTITLE${tcount}="
  result=`grep ^${trackdesc} $cddbfile`
  if [ "$result" ]; then
    # This elaborate section is necessary because very long titles may be
    # split over multiple lines.
    tracktitle=`grep "^${trackdesc}" $cddbfile | sed -e "s/^${trackdesc}//g" | tr -d '[:cntrl:]'`
    #echo "TITLE $tcount <$tracktitle>"
    if [ "$tracktitle" ]; then
      if [ $tcount -lt 9 ]; then
        trackfile=audio_0$(($tcount+1)).flac
      else
        trackfile=audio_$(($tcount+1)).flac
      fi
      if [ -f "$trackfile" ]; then
        if [ $writemode -eq 0 ]; then
          echo metaflac "$baseflags" $resettagswitch "$artistswitch" "$albumswitch" "$performerswitch" "$genreswitch" "$yearswitch" "--set-tag=TITLE=${valprotect}${tracktitle}${valprotect}" "$trackfile"
        else
          metaflac "$baseflags" $resettagswitch "$artistswitch" "$albumswitch" "$performerswitch" "$genreswitch" "$yearswitch" "--set-tag=TITLE=${valprotect}${tracktitle}${valprotect}" "$trackfile"
          numprocessed=$(($numprocessed+1))
        fi
      else
        echo "Trackfile $trackfile not found, skipping"
      fi
    else
      echo "Tracktitle $tcount empty, skipping"
    fi
    tcount=$(($tcount+1))
  else
    break
  fi
done

if [ $writemode -ne 0 ]; then
  echo "Tagged $numprocessed / $(($tcount)) files"
  touch .tagged
fi
