#!/bin/bash

# mp3titles.sh -a artist -l album file1 file2 ...

# Tags audio files according to given artist/album and the filename.
# Tracknumber and title tags are parsed from the filename,
# e.g. 04._Nothing_Else_Matters.mp3 has title="Nothing Else Matters".

# Currently uses mp3info2 for mp3 and musepack, and metaflac for flac.

# http://iki.fi/teknohog/hacks/

while getopts a:l: opt; do
    case "$opt" in
	a) artist="$OPTARG" ;;
	l) album="$OPTARG" ;;
	?) printf "Usage: %s -a artist -l album\n" $0 ;;
    esac
done

if [ ! -n "$album" ] || [ ! -n "$artist" ]; then
    printf "Usage: %s -a artist -l album\n" $0
    exit
fi
shift 4

for file in $@; do
    tracknumber="`echo $file | sed -e 's/\([0-9]\{1,2\}\)[\._-]\+\(.*\)\.\([A-Za-z0-9]\+\)/\1/' | sed -e 's/_/ /g'`"
    title="`echo $file | sed -e 's/\([0-9]\{1,2\}\)[\._-]\+\(.*\)\.\([A-Za-z0-9]\+\)/\2/' | sed -e 's/_/ /g'`"
    ext="`echo $file | sed -e 's/\([0-9]\{1,2\}\)[\._-]\+\(.*\)\.\([A-Za-z0-9]\+\)/\3/' | sed -e 's/_/ /g'`"

    case "$ext" in
	mp3|MP3|Mp3|mpc|MPC)
    #echo $file $title $artist $album
    #mp3info -t "$title" -a "$artist" -n "$tracknumber" -l "$album" $file
	    mp3info2 -t "$title" -a "$artist" -n "$tracknumber" -l "$album" $file
	    ;;
	ogg)
	    vorbiscomment -a -t artist="$artist" -t title="$title" -t album="$album" -t tracknumber="$tracknumber" $file 
	    ;;
	flac)
	    metaflac --set-tag=artist="$artist" --set-tag=title="$title" --set-tag=album="$album" --set-tag=tracknumber="$tracknumber" $file 
	    ;;
	esac
done