#!/bin/bash

# htmlrename
# - rename a html/directory pair, looking out for a few special characters
# - author: Steven A (stevenaaus@yahoo.com)

function Usage () {
    echo "usage: $Name oldbasename newbasename"
    echo "(do not include the .htm extension)"
}

Name=`basename $0`

if [ "$1" == "--" ] ; then
	shift
else 
	case "$1" in 
	    -* ) Usage ; exit 1 ;;
	esac
fi

if [ -z "$2" ] ; then 
    echo "$Name: missing arg(s)"
    exit 1
fi

if [ ! -f "$1.htm" -a ! -f "$1.html" -o ! -d "$1_files" ] ; then
    echo "$Name: \"$1.htm\",\"$1_files\" no such file(s)"
    exit 1
fi

if [ -f "$1.htm" ] ; then suffix=htm ; else suffix=html ; fi
                     
old="$1_files"
new="$2_files"

### first perform fetch-and-replace && then swap files
# the echo args must be in double-quotes to preserve  double spaces.

# sed doesn't like [ and ] ,  so '[' becomes '\['
old_1=`echo "$old" | sed -e 's/\[/\\\[/ ; s/\]/\\\]/'`

# some names use %20 instead of space,%27 for apostraphe and %21 for exclamation
# so we'll search for spaces and "%20" and "%27"
### this *doesn't* address every permutation of the regular character
### and it's ascii representation (eg " !" may be "%20!" and " %21")
old_2=`echo "$old_1" | sed -e 's/ /%20/g'`
old_3=`echo "$old_2" | sed -e "s/'/%27/g"`
old_4=`echo "$old_3" | sed -e "s/!/%21/g"`

# this ~shouldn't~ normally fail, excepting unforseen punctuation
if ! sed -e "s/$old_1\|$old_2\|$old_3\|$old_4/$new/g" "$1.$suffix" >/tmp/htmlrename$$
then
    echo "$Name: substitution failed, files unaltered."
    exit 1
else
    # don't kill old_html in case of failure (esp. vfat f/s)
    mv /tmp/htmlrename$$ "$2.$suffix" && \
    mv "$1.$suffix" /tmp/htmlrename && \
    mv "$old" "$new"
    exit $?
fi
