#!/bin/sh

#
# Recorre los directorios creando una playlist en cada directorio.
#

# Suggestions and comments are welcome: piotr@omega.resa.es
#
#    Copyright (C) Pedro Larroy 2002 piotr@omega.resa.es
#
#    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 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

#
#
#
# TODO:
# - Si no hay mp3 que no haga la playlist.
#

scan () {
  for file in *
  do
    if [ -d "$file" ]
    then
      cd "$file"
      #find -iname "*.mp3" -exec echo {}>playlist.m3u \;
      find -iname "*.mp3" > playlist.m3u 
      sort playlist.m3u > playlist.tmp
      mv playlist.tmp playlist.m3u
      if [ "$VERBOSE" = "YES" ]
      then  
        printf "creada playlist en `pwd`\n"
      fi
      scan 
      cd ..
    fi
  done
}

delete () {
  find -iname "playlist.m3u" | while read file
  do 
    rm -- "$file"
    if [ "$VERBOSE" = "YES" ]
    then  
      printf "borrada playlist: $file\n"
    fi
  done
}

usage () {
    printf "usage: $0 [OPTION] [DIRECTORY]
            
            Recorre los directorios creando una playlist en cada directorio.
            
            Options: 
            -d  delete
            -s  scan
            -v  verbose
            -h  this help\n"
}

while getopts ":vdsrw:" opt; do
  case $opt in
    v ) VERBOSE="YES" 
      ;;

    d ) DELETE="YES"
      ;; 

    s ) SCAN="YES"
      ;;

    \? ) usage 
      exit 1
      ;;

  esac

done
shift $(($OPTIND -1))

if [ -n "$1" ]
then
  cd "$1"
fi

if [ "$DELETE" = "YES" ]
then  
  delete
fi

if [ "$SCAN" = "YES" ]
then  
  scan
fi

if [ -z "$SCAN" ] && [ -z "$DELETE" ]
then 
  usage
fi

exit 0
