#!/bin/sh

trackinfo_dir=$1
music_dir=$2

if [ ! "$trackinfo_dir" ]
then
    echo "Give the location of the trackinfo dir."
    exit 1
fi

if [ ! "$music_dir" ]
then
    echo "Give the head of the music tree dir."
    exit 1
fi

IFS='
'
cd $trackinfo_dir

for file in $(find * -name '*.trk')
do
# url property encoding
#  '((" " . "+")
#    ("[" . "%5b")
#    ("]" . "%5d")
#    (")" . "%29")
#    ("!" . "%21")
#    ("#" . "%23")
#    (";" . "%3b")
#    ("," . "%2c")
#    ("(" . "%28")))
    #echo $trackinfo_dir/$file

    # Get the URL in xmms2's url property format
    url=$(echo $music_dir/$file |\
    sed -e 's;//*;/;g' -e 's/\.trk$//' -e 's;^;file://;' \
    -e "s/'/%27/g" -e 's/\&/%26/g' -e 's/[[]/%5b/g' \
    -e 's/[]]/%5d/g'  -e 's/[(]/%28/g' -e 's/[)]/%29/g' \
    -e 's/[!]/%21/g' -e 's/[#]/%23/g' -e 's/[;]/%3b/g' \
    -e 's/[,]/%2c/g' | \
    tr ' ' '+' \
    )
    #echo $url

    # Get the xmms2 id for the song.
    id=$(xmms2 mlib search url:'"'$url'"' | grep '^0' | tail -1 | \
    sed -e 's/|.*//' -e 's/^0*//')
    #echo "id: .$id."

    # We didn't find the id
    if [ ! "$id" ]
    then
	if [ ! -f "$music_dir/$(echo $file | sed 's/\.trk$//')" ]
	then
	    # But that's OK because there's no such file
	    continue
	else
	    #Hmm; a bit unfortunate
	    echo "The following is not found: $trackinfo_dir/$file -- $url"
	    continue
	fi
    fi

    ratings=$(grep -v '^_' $trackinfo_dir/$file | sed 's/:[0-9][0-9]*//g')

    for pair in $ratings
    do
	if [ "$(echo $pair | egrep '^(bridig2|ARJ|D|daltong|rj|root)=')" ]
	then
	    continue
	fi

	user=$(echo $pair | sed 's/=.*//')
	rating=$(expr 100 \* $(echo $pair | sed 's/.*=//'))

	if [ ! "$rating" -o "$rating" -eq 0 ]
	then
	    continue
	fi

	#echo "$id $user $rating"

	echo xmms2 mlib setint $id "rating."$user $rating "client/cluck"
	xmms2 mlib setint $id "rating."$user $rating "client/cluck"
    done

done
