#!/bin/sh

BINDIR=`dirname $0`

if [ -n "$BINDIR" ] ; then
    FABAN_HOME=`cd $BINDIR/.. > /dev/null 2>&1 && pwd`
    FENXI_HOME=`cd $FABAN_HOME/master/webapps/fenxi > /dev/null 2>&1 && pwd`
    export FABAN_HOME FENXI_HOME
fi

if [ -n "$JAVA_HOME" ] ; then
    PATH=$JAVA_HOME/bin:$PATH
    export PATH
fi

# Check and rename tool output that is not supposed to be .xan.
# Some older versions still use old format and should be named .log.
if [ $1 = "import" ] ; then
    IMPORTDIR="$2"
    cd ${IMPORTDIR}
            
    # For this trick, we need nawk or gawk.
    # Plain old awk usually does not work.
    # But we still fall back to it if
    # everything else falls apart.
    AWK=/usr/bin/awk
    if [ -x "/usr/bin/nawk" ] ; then
        AWK=/usr/bin/nawk
    elif [ -x "/usr/bin/gawk" ] ; then
        AWK=/usr/bin/gawk
    fi

    for i in *.xan.*
    do
        XANHEADER=`head -1 $i | ${AWK} -F ":" '{ print $1 }'`
        if [ "${XANHEADER}" != "Title" ] ; then
            TOOL=`echo $i | ${AWK} -F ".xan." '{ print $1 }'`
            HOST=`echo $i | ${AWK} -F ".xan." '{ print $2 }'`
            mv $i ${TOOL}.log.${HOST}
        fi 
    done
fi

chmod a+rx ${FENXI_HOME}/txt2db/*
chmod a+rx ${FENXI_HOME}/scripts/*

${FENXI_HOME}/scripts/fenxi $@


# TODO: This is a hack put in for FenXi for the time being.
# Need to remove when FenXi is fixed.

editXan() {
    if [ -f "${1}" ] ; then
        sed 's%FenXi.jpg%/fenxi/html/FenXi.jpg%g' ${1} > ${1}.1
        sed 's%/xanadu/html%/fenxi/html%g' ${1}.1 > ${1}
        rm ${1}.1
    fi
}

cd $2
for i in *.xan*.html
do
    editXan $i
done
for i in *.log.*.html
do
    editXan $i
done
cd ..
rm -rf txt

# end hack removal
