#!/bin/sh
# ChangeLog
# 0.2 - first working version
# 0.1 - initial version
#DEVICE MUST not end with /
DEVICE="/mnt/usb"
MTOOLS_DRIVE="D:"


if [ "$#" -ne 1 ] ; then
    echo "$(basename $0) version 0.2 by Michal Cihar <cihar at email dot cz>"
    echo "Script to generate playlist accepted by diva"
    echo "usage: $(basename $0) dir"
    echo "   dir ... directory name in $DEVICE"
    exit 100
fi

get_dos_name() {
# params: 1 = line from dir (mdir)
    DIRNAME=`echo "$1"|sed 's#^\([^[:space:]]\{1,8\}\)[[:space:]].*#\1#'`
    DIRTMP=`echo "$1"|sed 's#^.\{9\}\(.\{3\}\).*#\1#'`
#trim spaces ;-)
    DIREXT=`echo $DIRTMP`

    if [ "$DIREXT" ] ; then
        DIR=$DIRNAME.$DIREXT
    else
        DIR=$DIRNAME
    fi
    echo $DIR
}

gen_pl_main() {
# params: 1 = dir, 2= path
    LIST=`mdir "$1"|tail +7`
    if ( echo "$LIST" | grep -q '<DIR>' ) ; then
        echo "$LIST" | grep '<DIR>' | while read LINE ; do
            NEXTDIR=`get_dos_name "$LINE"`
            gen_pl_main "$1/$NEXTDIR" "$2/$NEXTDIR"
        done
    fi
    echo "$LIST" | grep -v '<DIR>' | grep '^.\{8\} MP3' | while read FLINE ; do
        echo -n "$2/"
        get_dos_name "$FLINE"
    done
    
}

DIRLINE=`mdir "$MTOOLS_DRIVE"|grep '<DIR>'|grep "$1\$"`

MYDIR=`get_dos_name "$DIRLINE"`

echo "Creating playlist $DEVICE/$1.pl"

gen_pl_main "$MTOOLS_DRIVE/$MYDIR" "/$MYDIR" > "$DEVICE/$1.pl"
todos "$DEVICE/$1.pl"
