#!/usr/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" -a ! -f "$1.shtml" -a ! -f "$1" -o \( ! -d "$1_files" -a ! -d "$1_data" \) ] ; then
    echo "$Name: \"$1.htm\",\"$1_files\" no such file(s)"
    exit 1
fi

if    [ -f "$1.htm" ] ; then suffix=.htm
elif [ -f "$1.html" ] ; then suffix=.html
elif [ -f "$1.shtml" ] ; then suffix=.shtml
else suffix=""
fi

if [ -f "$2.html" -o -f "$2.htm" ] ; then
    echo "$Name: \"$2$suffix\" already exists!"
    exit 1
fi

                     
if [ -d "$1_files" ] ; then
  old="$1_files"
else
  old="$1_data"
fi
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 '\['
old1=`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")
old2=$(echo "$old1" | sed -e 's/ /%20/g')
old3=$(echo "$old2" | sed -e "s/'/%27/g")
old4=$(echo "$old3" | sed -e "s/!/%21/g")
old5=$(echo "$old4" | sed -e "s/\`/%60/g")
old6=$(echo "$old5" | sed -e "s//%BB/g")

# this ~shouldn't~ normally fail, excepting unforseen punctuation
if ! sed -e "s/$old1\|$old2\|$old3\|$old4\|$old5\|$old6/$new/g" "$1$suffix" >/tmp/htmlrename$$
then
    echo "$Name: substitution failed, files unaltered."
    exit 1
else
    # don't kill oldhtml in case of failure (esp. vfat f/s)
    (if [ -z "$suffix" ] ; then
	# f-ing firefox insists on saving without the .htm extension, so if there's no ".htm" , add it
	mv /tmp/htmlrename$$ "$2.htm"
     else
	mv /tmp/htmlrename$$ "$2$suffix"
     fi ) && \
    mv "$1$suffix" /tmp/htmlrename && \
    mv "$old" "$new"
    exit $?
fi
