#!/bin/sh
#
# Shell scirpt for building .wo files from .gwsc files
#

case $2 in
    clean)
        echo "Cleaning " *.wo *.lproj/*.wo GSWWOReplaceScript.sed
        rm -rf *.wo *.lproj/*.wo GSWWOReplaceScript.sed
    ;;
    '')
        # An sed script to convert the classes refered to in .gswd files
        # from their GSW- to their WO-representations based on the mappings
        # contained in the GSWWOCompatibility.h header.
        # Currently this script is rather aggresive as it doesn't identify
        # whole words but merely patterns.
        grep "^#define[[:space:]]*GSW.*[[:space:]]*WO.*" ../GSWeb.framework/GSWWOCompatibility.h |
                  sed -e 's/#define /s\//' \
                      -e 's/[[:space:]*]/\//' \
                      -e 's/[[:space:]*]//g' \
                      -e 's/$/\//' > GSWWOReplaceScript.sed

        if [ $1 = "GSWExtensions" ]; then
            echo "s/GSWExtensions/WOExtensions/g" >> GSWWOReplaceScript.sed
            change_prefix="-e s/GSW/WO/g"
        else
            echo "s/GSWExtensionsGSW/WOExtensionsGSW/g" >> GSWWOReplaceScript.sed
            change_prefix=""
        fi

        # The script is copied instead of referenced as the relative path
        # from the $@ directory is unknown.

        for gswc in `ls -d *.gswc *.lproj/*.gswc`; do
                wo=`echo $gswc | sed -e 's/\.gswc/.wo/g' ${change_prefix}`
                echo "Copying $gswc to ${wo}..."
                rm -rf "$wo" &&
                cp -r "$gswc" "$wo" &&
                cp GSWWOReplaceScript.sed "$wo" &&
                (
                  cd "$wo" &&
                  # Run script on .gswd files and rename to .wod:
                  for I in *.gswd ; do
                    if [ -e $I ]; then
                      sed -f GSWWOReplaceScript.sed $I > `echo $I | sed 's/gswd$/wod/'` &&
                      rm -f $I
                    fi
                  done
                  rm -rf CVS GSWWOReplaceScript.sed
                  # Convert gsweb tags to webobject tags:
                  for I in *.html ; do
                    if [ -e $I ]; then
                      sed -e 's/<gsweb/<webobject/g' -e 's/<\/gsweb/<\/webobject/g' $I > ${I}.tmp && mv ${I}.tmp $I
                    fi
                  done
                  # Rename .gswi files to .woo: 
                  for I in *.gswi ; do
                    if [ -e $I ]; then mv $I `echo $I | sed "s/gswi$/woo/"`; fi
                  done
                  # Rename files to change GSW prefix to WO:
                  for I in GSW* ; do
                    if [ -e $I ]; then mv $I `echo $I | sed ${change_prefix}`; fi
                  done
                )
        done
    ;;
    *)
        echo "error: Unknown build action: '$1'" 1>&2
        exit -1
esac
