#!/bin/sh
# lowercase_filenames - a shell script to convert filenames to lower case
# underscore_filenames - a shell script to change blanks to underscores
# Author: Christian Steinruecken <cstein@suse.de>
#

self=`basename $0`
force=""
verbose=""

convert() {
  x="$1"
  # convert to lowercase
case $self in
	lowercase_filenames)
	newname=`echo "$x" | tr '[A-Z]' '[a-z]'`
	;;
	underscore_filenames)
	newname=`echo "$x" | tr '[:blank:]' '_'`
esac	
  if [ ! "$x" = "$newname" ]; then
    # preserve time stamp
    realdate=`date +%Y%m%d%H%M.%S -r "$x"`
    # this is required on VFAT partitions
    [ -n "$verbose" ] && echo "$x -> $newname"
    mv -i "$x" "${newname}__N_E_W__"
    mv -i "${newname}__N_E_W__" "${newname}"
    # restore time stamp
    touch -m -t "${realdate}" "${newname}"
  fi
}

alpha() {
  y="$1"
  b=`basename "$1"` 
  if [ -e "$y" ]; then
    if [ "$force" = "1" ]; then
      convert "$y"
    else
      if [ "$b" = "Makefile" -o "$b" = "Mail" ]; then
         echo "$self: $y: Cowardly refusing to convert this (use --force)..." >&2
      elif [ ! -f "$y" -a ! -d "$y" ]; then
         echo "$self: $y: Special file, skipping..." >&2
      else
         convert "$y"
      fi
    fi
  else
    echo "$self: $y: No such file or directory." >&2
  fi
}



show_help() {
echo "Usage: $self [options] [files...]"

case $self in
	lowercase_filenames)
	echo "Converts filenames to lowercase."
	echo "Options must be specified BEFORE the files."
	;;
	underscore_filenames)
	echo "Converts blanks in filnames to underscores."
esac

echo "If no files are given, all files in the current working directory will be"
echo "used. Options include:"
echo
echo "   -v, --verbose     Verbose operation"

if [ $self == lowercase_filenames ]; then
echo "   -f, --force       Also convert Makefiles, hidden and special files"
fi

echo "   -h, --help        Display this help"
echo
}

while [ -n "$1" ]; do
case "$1" in
"-h"|"--help") show_help; exit 0 ;;
"-f"|"--force") force="1"; shift ;;
"-v"|"--verbose") verbose="1"; shift ;;
*) break ;;
esac
done

if [ -n "$*" ]; then
   # convert all files (given as parameters)
   for i in "$@"; do
     alpha "$i"
   done
 else
   # take all files in current working directory
   if [ -n "$force" ]; then
     for i in .* *; do
       alpha "$i"
     done
   else
     for i in *; do
       alpha "$i"
     done
   fi
fi
exit 0
