#!/bin/sh
UNSET="-UNSET-"

pname="$0"
pname="`basename $pname`"
pwhit="`echo $pname|sed -e 's/./ /g'`"



function usage {
    echo ""
    echo "Usage:"
    echo ""
    echo "${pname} [--new-prefix=NEWFIX|--old-prefix=OLDFIX|--relative] "
    echo "${pwhit} directory"
    echo ""
    echo "Will recursively process all files with extensions:"
    echo ".html .shtml and .htm, replacing absolute href and src"
    echo "by relative one (by default), or by substituting OLDFIX by NEWFIX."
    echo ""
}



function process {
    CURDIR="$1"
    RELATIVE="$2"
    OLDFIX="$3"
    NEWFIX="$4"

    case "$CURDIR" in
    */)
        ;;
    *)
        CURDIR="$CURDIR/"
        ;;
    esac

    FILTER='-name "*.'`echo $EXTENSIONS|sed -e 's/,/" -o -name "*./g'`'"'
    find $CURDIR -type f \
    \( -name '*.html' -o -name '*.htm'  -o -name '*.shtml' \) \
    -print | while read file ; do
        echo Processing $file
        if [ $RELATIVE -eq 1 ] ; then
            DIRRELPATH=`echo "$file"|sed -e "s|$CURDIR||"`
            FILE="`basename $DIRRELPATH`"
            DIRS="`dirname $DIRRELPATH`"
            if [ "$DIRS" = "." ] ; then
                RELPATH=""
            else
                RELPATH=`echo "$DIRS"|sed -e 's|[^/][^/]*|..|g'`/
            fi
            OLDFIX="/"
            NEWFIX="$RELPATH"
        fi
        mv $file $file~
        sed \
        -e 's|[hH][rR][eE][fF]=\(["'\'']*\)'"$OLDFIX"'|HREF=\1'"$NEWFIX"'|g' \
        -e 's|[sS][rR][cC]=\(["'\'']*\)'"$OLDFIX"'|SRC=\1'"$NEWFIX"'|g' \
        < $file~ > $file
    done
}



if [ $# -eq 0 ] ; then
    usage
    exit 1
fi

RELATIVE=1
NEWFIX="$UNSET"
OLDFIX="$UNSET"
CURDIR=""

for arg ; do
    case "$arg" in
    --relative)
        RELATIVE=1
        ;;
    --new-prefix=*)
        NEWFIX="`echo $arg|sed -e 's/.*=//'`"
        RELATIVE=0
        ;;
    --old-prefix=*)
        OLDFIX="`echo $arg|sed -e 's/.*=//'`"
        RELATIVE=0
        ;;
    --help)
        usage
        exit 0
        ;;
    -*)
        echo ""
        echo "${pname}: invalid option ${arg}."
        usage
        exit 1;
        ;;
    *)
        if [ $RELATIVE -eq 0 \
            -a \( "$OLDFIX" = "$UNSET" -o "$NEWFIX" = "$UNSET" \) ] ; then
            echo ""
            echo "${pname}: Either --relative or both --new-prefix and "
            echo "${pwhit}  --old-prefix must be specified."
            usage
            exit 2
        fi
        CURDIR="$arg"
        if [ ! -d "$CURDIR" ] ; then
            echo ""
            echo "${pname}: ${CURDIR} is not a directory."
            usage
            exit 3
        fi
        process "$CURDIR" "$RELATIVE" "$OLDFIX" "$NEWFIX"
        ;;
    esac

done

exit 0
ViewGit