#!/bin/sh

ISCCDST=${HOME}/.iscc_wine
ISINST=/usr/share/iscc/isetup-5.4.3.exe

isccpath() {
    find "${ISCCDST}" -name ISCC.exe 2>/dev/null
}

kill_gecko_dialog() {
    while true ; do
        DPID=`ps ax|grep install_gecko|grep -v grep|awk '{print $1}'`
        test -z "$DPID" || kill $DPID > /dev/null 2>&1
        sleep 1
    done
}

XVFBPID=
ISCCERR=/tmp/.isccerr.$$
XVFBERR=/tmp/.xerr.$$

cleanup() {
    test -z $XVFBPID || kill $XVFBPID
    test -f $XVFBERR && rm -f $XVFBERR || :
    test -f $ISCCERR && rm -f $ISCCERR || :
}

trap cleanup EXIT

# Fire up Xvfb and remeber its PID in XVFBPID
DPYNUM=0
AA=
while test $DPYNUM -lt 99 ; do
    Xvfb :$DPYNUM 2>$XVFBERR &
    XVFBPID=$!
    sleep 1
    AA=`grep 'already active for display' $XVFBERR`
    if test -z "$AA" ; then
        break;
    fi
    DPYNUM=`expr $DPYNUM + 1`
done
if test -n "$AA" ; then
    XVFBPID=
    echo "Could not start Xvfb" >&2
    exit 1
fi

export DISPLAY=:$DPYNUM
export WINEPREFIX=$ISCCDST
export WINEDEBUG=-all
if [ -z "`isccpath`" ] ; then
    echo "Installing InnoSetup in $ISCCDST ..."
    rm -rf "${ISCCDST}"
    kill_gecko_dialog &
    GKPID=$!
    wine "${ISINST}" /verysilent 2>/dev/null
    disown $GKPID
    kill $GKPID
fi
if [ -z "`isccpath`" ] ; then
    echo "Could not find or install ISCC" >&2
    exit 1
fi

# Define BADWINE, if we got a wine with a NULL-resource bug.
WINE_VERSION=`wine --version|sed -e 's/wine-//'|tr . 0`
BADWINE=
if [ $WINE_VERSION -lt 103021 ] ; then
    BADWINE=-dBADWINE=1
fi

# ISCC currently crashes with a fake "Out of memory" when running
# under wine. This wrapper loops up to MAX times until ISCC finished
# successfully.
CNT=0
MAX=5

while test $CNT -lt $MAX ; do
    wine "`isccpath`" "$@" $BADWINE 2>$ISCCERR
    R=$?
    case $R in
        0)
            cat $ISCCERR >&2
            exit 0;
            ;;
        *)
            cat $ISCCERR >&2
            OMM=`grep "Out of memory" $ISCCERR`
            test -z "$OMM" && exit $R
            echo "ISCC got out of memory, retrying ..."
            sleep 2
            CNT=`expr $CNT + 1`
            ;;
    esac
done
