#! /bin/sh
# #############################################################################

       NAME_="neatname"
       HTML_="rename files script"
    PURPOSE_="neatly rename files"
   SYNOPSIS_="$NAME_ [-vhl] -p <prefix> -i <integer> -s <suffix> <file> [file...]"
   REQUIRES_="standard GNU commands"
    VERSION_="1.3"
       DATE_="1998-10-12; last update: 2005-06-15"
     AUTHOR_="Dawid Michalczyk <dm@eonworks.com>"
        URL_="www.comp.eonworks.com"
   CATEGORY_="file"
   PLATFORM_="Linux"
      SHELL_="bash"
 DISTRIBUTE_="yes"

# #############################################################################
# This program is distributed under the terms of the GNU General Public License

usage () {

echo >&2 "$NAME_ $VERSION_ - $PURPOSE_
Usage: $SYNOPSIS_
Requires: $REQUIRES_
Options:
     -p, prefix to use on file names
     -i, integer number to start with
     -s, file suffix to use on file names
     -v, verbose
     -h, usage and options (this help)
     -l, see this script"
    exit 1
}

# args check
[ $# -eq 0 ] && { echo >&2 missing argument, type $NAME_ -h for help; exit 1; }

# var init
verbose=
prefix=
suffix=

# option and argument handling
while getopts vhlp:i:s: options; do

    case "$options" in
        p) prefix="$OPTARG" ;;
        i) int="$OPTARG" ;;
        s) suffix="$OPTARG" ;;
        v) verbose=on ;;
        h) usage ;;
        l) more $0; exit 1 ;;
       \?) echo invalid argument, type $NAME_ -h for help; exit 1 ;;
    esac

done
shift $(( $OPTIND - 1 ))

# int check
[[ $int == *[!0-9]* ]] && { echo >&2 the argument to option -i must be an integer; exit 1; }

# args check: any files to work on?
[[ $@ ]] || { echo >&2 no files specified, type $NAME_ -h for help; exit 1; }

# main execution
for a in "$@"; do
    
    newf="${prefix}"${int}"${suffix}"
    if [ -f "$newf" ]; then
        echo "${NAME_}: skipping renaming $a - $newf already exist" && continue
    else
        [ -f "$a" ] && { mv "$a" "$newf"; } || continue
        [[ $verbose ]] && echo "${NAME_}: $a -> $newf"
    fi
    ((int++))

done
