#!/bin/sh

# please read the copyright notice before you change anything 

copyright_notice()
{
    echo "copyleft 2004-2007 Ricardo Birmann"
    echo "This is free software and is distributed under the terms of"
    echo "the GNU General Public Liscence. You are encouraged to change"
    echo "and/or distribute it under the terms of such liscence, which"
    echo -e "can be found at: http://www.gnu.org/copyleft/gpl.html\n"
    echo -e "For bug reports, email me at ricardobirmann(at)ricardobirmann.com\n"
    echo "I'd be happy to see any modifications you've made to this"
    echo "program, so please email me if you have changed it..."
    return
}

# current version is

version="1.5.1"

# see the version log / to-do list at end of this file

help_m3umaker()
{
    echo -e "usage: $0 \n\t\t[[-d dir][[-g|-G]|[-p|-P]][-o filename][-v]"
    echo -e "\t\t[-u [amarok|xmms]|[-E enqueueCommand][-X playCommand]][-e|-x]|"
    echo -e "\t\t[-h]|[-V]|[-c]]\n"

    echo -e "===== PLAYLIST OPTIONS\n"
    echo -e "\t-p string with aditional acceptable filename terminations ('.mp3 .Mp3 .mP3 .MP3' will allways be included)"
    echo -e "\t-P string containing the only acceptable filename terminations"
    echo -e "\t-g include .ogg files as well as .mp3 files (same as -p '.ogg .Ogg .OGG')"
    echo -e "\t-G include .ogg files instead of .mp3 files (same as -P '.ogg .Ogg .OGG')"
# echo " *  -a recursively add all songs to a single playlist (-r implied)"
# echo " *  -r recursive"
    echo -e "\t-d use dir as the working directory (defaults to current)"
    echo -e "\t-o output file name (no path!! it will allways be placed under the working direcory)"
    
    echo -e "\n\tThe output file will be placed under the directory specified by the -d option (current directory, when such option is ommited) and will be named '!dir.m3u' if the current working directory is something like '/home/media/music/dir/' and the -o option is not used.\n"
    
    echo -e "===== PLAYER INTEGRATION OPTIONS\n"
    echo -e "\t-u player to use (currently supports amarok and xmms), default is xmms"
    echo -e "\t-e enqueue the created file to the current playlist"
    echo -e "\t-x enqueue the created file to the current playlist and play it :)"    
    echo -e "\t-E specify the enqueue command (more details below)"
    echo -e "\t-X specify the play command (more details below)"
    
    echo -e "\n\tThe -E and -X options allow one to enqueue and play the created m3u playlist on any scriptable player that is currently unsupported by the -u option.\n"
    
    echo -e "\tExamples:"
    echo -e "\t\t\$ $0 -E \"/usr/bin/player --enqueue\" -o p.m3u"
    echo -e "\t\t...will result in the following system call:"
    echo -e "\t\t/usr/bin/player --enqueue p.m3u\n"
    echo -e "\t\t\$ $0 -X \"/usr/bin/player --play\" -o p.m3u"
    echo -e "\t\t...will result in the following system call:"
    echo -e "\t\t/usr/bin/player --play p.m3u\n"
    
    echo -e "\tNote that option -E implies -e and -X implies -x!\n" 
    
    echo -e "===== OTHER OPTIONS\n"
    echo -e "\t-v verbose on"
    echo -e "\t-h this help text"
    echo -e "\t-c copyright and contact information"
    echo -e "\t-V current version\n"
    
    

# echo "* Please note: the options -a and -r have not been implemented yet"
    echo -e "\ncopyleft Ricardo Birmann 2004-2007 (see also $0 -c)\n"
    return
}


add_all() # has to be modified to support options -a and -r -> filenames must have path
{
    for j in $list ; do
	if find -L "$basedir" | grep $j > /dev/null ; then 
	    for i in "$basedir"/*"$j"; do
	    echo "$i" >> "$m3ufile";
	    let "songcount += 1"
	    if $verbose ; then echo $i; fi
	    done;
	fi ;
    done;
    return
}

#recurs=false
#useall=false
list=' .mp3 .Mp3 .mP3 .MP3 '
basedir=`pwd`
verbose=false
enqueueit=false
playit=false
m3ufile=  # set this var to a null value
songcount=0
# default player is xmms, so...
enqueueCommand="xmms -e"
playCommand="xmms -e -p"
while getopts acd:egGho:p:P:rvVxu:E:X: opt
  do
  case "$opt" in
      h) help_m3umaker
	  exit 0;;
      V) echo "$version"
	  exit 0;;
      c) copyright_notice
	  exit 0;;
      v) verbose=true;;
#  r) recurs=true;;
#  a) useall=true
#     recurs=true;;
      g) list=$list' .ogg .Ogg .OGG';;
      G) list='.ogg .Ogg .OGG';;
      p) list=$list' '$OPTARG;;
      P) list=$OPTARG;;
      d) 
	  basedir=$OPTARG
	  if [ ! -d $basedir ]; then
	      echo "$basedir is not a valid directory, displaying help text..."
	      help_m3maker
	      exit 1
	  fi
	  if test "${basedir:${#basedir}-1:1}" = "/" ; then  # we want the dir name without a final backslash
	      basedir=${basedir:0:${#basedir}-1}
	  fi
	  ;;
      u) player=$OPTARG
	  case "$player" in
	      amarok)
		  enqueueCommand="dcop --user `whoami` amarok playlist addMedia"
		  playCommand="dcop --user `whoami` amarok playlist playMedia"
		  ;;
	      xmms)
		  enqueueCommand="xmms -e" # should be set already
		  playCommand="xmms -e -p" # should be set already
		  ;;
	      [?])
	      echo "Unsupported player, displaying help text..."
	      help_m3umaker
	      exit 1
	      ;;
	  esac
	  ;;
      E) enqueueCommand=$OPTARG
	  enqueueit=true;;
      X) playCommand=$OPTARG
	  playit=true;;
      o) m3ufile=$OPTARG;;
      e) enqueueit=true;;
      x) 
	  enqueueit=true
	  playit=true;;
      [?]) 
      echo "unknown option, displaying help text..."
      help_m3umaker
      exit 1
      ;;
  esac
done

if [ ! "$m3ufile" ]  ; then
    m3ufile='!'`basename "$basedir" | tr ' ' '_'`.m3u
fi

shift `expr $OPTIND - 1`

m3ufile=$basedir/$m3ufile

if [ -f "$m3ufile" ]; then
    echo -n "$m3ufile exists, overwrite? [Y/n] "
    read answer
    if  test "$answer" = "n" -o "$answer" = "N" ; then
	echo "ok, then... aborting..."
	exit 0
    fi
    rm "$m3ufile"
fi

if $verbose ; then  echo "Running; acceptable filename terminations are: ""$list"; fi
if $verbose ; then  echo "Current working directory is ""$basedir"; fi
if $verbose ; then  echo -n "Creating output file $m3ufile..."; fi

echo "# Created with m3uMaker" > "$m3ufile" ;
echo "# http://ricardobirmann.com/" > "$m3ufile" ;
if $verbose ; then  echo "done" ; fi

if $verbose ; then  echo "Adding songs:" ; fi

add_all

if $verbose ; then  echo "Playlist sucessfully created with $songcount files" ; fi

if $playit ; then
    if $verbose ; then echo -n "Adding file to playlist..."; fi
    $playCommand "$m3ufile"
    if $verbose ; then echo "done"; fi
elif $enqueueit ; then
    if $verbose ; then echo -n "Adding file to playlist..."; fi
    $enqueueCommand "$m3ufile"
    if $verbose ; then echo "done"; fi
fi

if $verbose ; then echo "Exiting with sucessfull status 0" ; fi
exit 0


# VERSION LOG
# (to-do list, in the case of future versions; current version: <- )
#
# 2.6
#   option -3 -> check ID3 tag of each file to determine track number (useful when filenames do not contain such information and we want to play the songs of an album, obviously, in order)
#
# 2.5
#   filename sent through parameter -o accepts wildcards %d (dir name), %n (number of songs), %N (number of dirs), etc...
#
#   output file can be placed anywhere (songs with absolute path in .m3u file)
#
# 0.2
#   recursive options -r and -a working
#   trap exit signal C-c understood
#
# 1.5.1 <- 
#   bug fixed, if base directory was symbolic link, empty playlist was created
#
# 1.5 
#   support for amarok (option -u implemented)
#
# 1.3
#   -V option: display current version
#   -c option: copyright and contact information notice
#   synopsis corrections on help text:
#        1) -p and -P should not be used together
#        2) same for -g and -G
#        3) one should use -h OR -V OR -c OR anything else
#        4) -p/-P and -g/-G should not be used simultaneously
#        5) no longer showing information on options -a and -r, which are not implemeted yet
#
# 1.2 
#   output name defaults to !directory_name.m3u instead of !playlist.m3u
#   song count available on verbose mode
#   bug fixed: files/directories with more then one consecutive spaces (' ') handled properly
#
# 1.1
#   new parameters -p, -P and -G
#
# 1.0 
#   available parameters -d, -e, -g, -h, -o, -v and -x
