#!/bin/sh
#$Revision: 1.9 $
DATADIR=/mnt/phatdata
#DATADIR=/usr/local/mp3
OUTDIR=/dos/data
tmpfile=/tmp/builddb

# If no artist tag in ID3, try to grab it from the filename.  This works if
# the filename follows the format "Artist - Filename.mp3"
fixartist=true

export LC_ALL=C  # makes sort and strcmp work together.

> $tmpfile

[ -e $DATADIR/tracks.db ] && cat $DATADIR/tracks.db > $tmpfile

find $DATADIR -type f -iname '*mp3' | (while read a
do
if grep "	""$a" $tmpfile
then
  echo $a >/dev/null
  #echo $a in $tmpfile 1>&2
else
  echo $a not in $tmpfile 1>&2
  id3=/tmp/id3.$$
  id3tool "$a" | grep -Ei "title|artist|album|year|genre|track" > $id3
  title=$(cat $id3 | grep -i title: | cut -c 13- | sed 's/ *$//')
  [ -z "$title" ] && title="Unknown Title"
  artist=$(cat $id3 | grep -i artist: | cut -c 10- | sed 's/ *$//')
  [ -z "$artist" ] && artist="Unknown Artist"
  album=$(cat $id3 | grep -i album: | cut -c 9- | sed 's/ *$//')
  [ -z "$album" ] && album="Unknown Album"
  year=$(cat $id3 | grep -i year: | cut -c 8- | sed 's/ *$//')
  genre=$(cat $id3 | grep -i genre: | cut -c 9- | sed 's/(.*)//' | sed 's/ *$//')
  [ -z "$genre" ] && genre="Unknown Genre"
  track=$(cat $id3 | grep -i track: | cut -c 9- | sed 's/ *$//')
  [ -z "$track" ] && track=0
  [ "$track" -eq 0 ] && track="Unknown Track"
  rm -f $id3
  info=/tmp/mp3head.$$
  mp3header "$a" | grep -Ei "size|time|bitrate|freq" > $info
  size=$(cat $info | grep -i size | tr -dc [0-9])
  time=$(cat $info | grep -i time | tr -dc [0-9])
  [ -z "$time" ] && time=0
  bitrate=$(cat $info | grep -i bitrate | tr -dc [0-9])
  freq=$(cat $info | grep -i freq | tr -dc [0-9])
  rm -f $info
  if $fixartist && [ "$artist" = "Unknown Artist" ]
  then
    echo Finding artist 1>&2
    newartist=$(basename "$a" | cut -d '-' -f 1)
    echo Trying $newartist 1>&2
    if echo $newartist | egrep '\(|\)' &>/dev/null
    then
      echo Found paren 1>&2
    else
      echo Checks good - $newartist 1>&2
      artist=$newartist
    fi
  fi
  echo -e "$(echo $a|sed "s%$DATADIR%$OUTDIR%")\t${title}\t${artist}\t${album}\t${genre}\t${time}\t${a}\t${track}"
fi
done
) > $tmpfile.new
cat $tmpfile.new | sed 's/ \*/*/g' > $tmpfile
cat $tmpfile > $DATADIR/tracks.db
cat $tmpfile | sort -f -t '	' -k 3,3 -k 4,4 -k 8,8n -k 7,7 > $DATADIR/artist.db
cat $tmpfile | sort -f -t '	' -k 3,3 -k 4,4 -k 8,8n -k 7,7 > $DATADIR/album.db
cat $tmpfile | sort -f -t '	' -k 5,5 -k 3,3 -k 4,4 -k 8,8n -k 7,7 > $DATADIR/genre.db
