#!/bin/bash

. buildsys/functions

ProcessArgs $*
Assert LoadConfigs
Assert SetupLogDir
Assert SetupResFile

uninstall()
{
   INSTALL_DIR=$1
   UNINSTALLER_FILE=

   # Check if the uninstaller exists (Only if installed with bitrock installer)
   echo "checking for file $UNINSTALLER_NAME ..."
   if [ -f "$UNINSTALLER_NAME" ]
   then
       UNINSTALLER_FILE=$UNINSTALLER_NAME
   elif  [ -f "$UNINSTALLER_NAME.exe" ]
   then
       UNINSTALLER_FILE=$UNINSTALLER_NAME.exe
   else
       echo "$UNINSTALLER_NAME does not exist"
   fi

   # If the uninstaller exists, call onto it to remove the distribution
   if  [ -n "$UNINSTALLER_FILE" ]
   then
       echo "backing up installation directory"
       ( cd "$WORKDIR" && tar -cf installed.tar "${INSTALL_DIR}" )

       echo "running $UNINSTALLER_FILE --mode unattended..."
       if [ "$CURRENT_PL_DARWIN" != "" ]
       then
           "$UNINSTALLER_FILE"/Contents/MacOS/installbuilder.sh --mode unattended
       else
           "$UNINSTALLER_FILE" --mode unattended
       fi

       if [ $? = 0 ]
       then
           # the uninstaller creates a bitrock log which is not removed even
           # if removeLogFile is set, that just seems to work for the installer
           # and not the uninstaller.  So just remove the file from the 
           # uninstaller here.
           rm -rf /tmp/bitrock_installer*
           echo "Uninstall completed"
       else
           echo "ERROR: Uninstall failed"
           exit 1
       fi
   fi
}

SHORTSETUP=`echo $SETUP_TYPE | sed 's/-release//'`

#Need to source the RELEASE info in order to get the details required for the 
#setting of the VORTEX_INSTALL_DIR
. $DEPWORKDIR/release_info/RELEASE

CURRENT_PL_CYGWIN=`uname | grep CYGWIN`

EDITION=

if [ -d "$WORKDIR/$EXAMPLE_INSTALL_DIR/Vortex$VORTEX_VERSION/Device/VortexOpenSpliceRTE" ]
then
   EDITION=RTE
fi

if [ "$CURRENT_PL_CYGWIN" != "" ]
then
    VORTEX_INSTALL_DIR=$PACKAGE_VERSION
else
    VORTEX_INSTALL_DIR=Vortex$VORTEX_VERSION/Device/VortexOpenSplice$EDITION/$PACKAGE_VERSION
fi

SFX=""
if [ "$CURRENT_PL_DARWIN" != "" ]
then
   SFX=".app"
fi

UNINSTALLER_NAME="$WORKDIR/$EXAMPLE_INSTALL_DIR/$VORTEX_INSTALL_DIR/uninstall-$SHORTSETUP-HDE$SFX"

if [ -f "$UNINSTALLER_NAME" ]
then
    echo "Uninstalling HDE..."
    uninstall $EXAMPLE_INSTALL_DIR/$VORTEX_INSTALL_DIR
fi

UNINSTALLER_NAME="$WORKDIR/$EXAMPLE_INSTALL_DIR/$PACKAGE_VERSION/uninstall-$SHORTSETUP-TEST"

if [ -f "$UNINSTALLER_NAME" ]
then
    echo "Uninstalling TEST ..."
    uninstall $EXAMPLE_INSTALL_DIR/$PACKAGE_VERSION
fi

UNINSTALLER_NAME="$WORKDIR/$RTS_INSTALL_DIR/$VORTEX_INSTALL_DIR/uninstall-$SHORTSETUP-RTS$SFX"

if [ -f "$UNINSTALLER_NAME" ]
then
    echo "Uninstalling RTS..."
    uninstall $RTS_INSTALL_DIR/$VORTEX_INSTALL_DIR
fi
