#!/bin/sh
# mkvpls - Create a video playlist of files based on MIME type.
#
# Note: You must associate FILEEXT with your prefered application in GNOME.
#    Examples: .vpls opens with "totem", "xine -P", "mplayer -playlist"
#              .m3u opens with "xmms", "totem", "rhythmbox"
#
# Copyright 2004-2005 David L Norris <dave@webaugur.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

# File types to find
MIMETYPE="video/*"
# Playlist File Extension
FILEEXT="m3u"

if [ ! -d "$1" ]; then
    echo "usage: mkvpls </path/to/directory>";
    exit
fi

ROOTDIR="$1"

TMPFILE=`mktemp "${1}/../.playlist.XXXXXXXXXX"` || gdialog --infobox "Unable to Create Playlist" 100 100
if [ ! -f "$TMPFILE" ]; then exit; fi

echo $TMPFILE

# Field seperation on newline only
OLDIFS=$IFS
IFS="
"
    # Erase existing playlist
    echo > "${TMPFILE}"

    # Find all the video files
    for i in `find ${ROOTDIR} -type f | sort`;
    do
       # If the file is not really a video don't bother
       ISVIDEO=1
       file -bi "${i}" | grep "^${MIMETYPE}" > /dev/null
       ISVIDEO=$?
       if [ $ISVIDEO != 0 ]; then
#           echo "-NonVideo: ${i}" 1>&2
           continue;
       fi

       echo "${i}" >> "${TMPFILE}"

    done

if [ -f "${TMPFILE}" ]; then
    mv "${TMPFILE}" "${ROOTDIR}.${FILEEXT}"
else
    gdialog --infobox "Unable to Create Playlist" 100 100
    rm -f "${TMPFILE}"
fi

