#!/bin/bash

# keep track of if we have to warn user to run setup in a new terminal
ORIG_GSDL3SRCHOME=$GSDL3SRCHOME

extension=$1

#echo "ORIG_GSDL3SRCHOME: |$ORIG_GSDL3SRCHOME|"

# for every extension passed in, check if extension folder exists
# and contains a build file, then run ant (de)activate or equivalent,
# and on success rename the extension folder to extension.inactive
#
# https://unix.stackexchange.com/questions/72039/whats-the-difference-between-single-and-double-equal-signs-in-shell-compari
# https://stackoverflow.com/questions/8880603/loop-through-an-array-of-strings-in-bash
#
echo "Deactivating extension $extension"
if [ ! -d "$extension" ] ; then
    echo "Deactivate failed: Extension $extension does not exist"
    exit 1
fi
if [ ! -f "$extension/build.xml" ] ; then
    echo "Deactivate failed: No build.xml exists in extension $extension"
    exit 2
fi

pushd "$extension" > /dev/null
exitval=0
for cmd in deactivate del-extension del-service; do
    echo "Attempting to run ant $cmd on the extension $extension..."
    ant $cmd > /dev/null 2>&1
    if [ "$?" = "0" ] ; then
     	echo "Finished deactivating extension $extension"
	
	# print out any helpful information provided by the extension about warnings
	# associated with deactivation (what things might no longer work, for example)
	if [ -f "DEACTIVATED.txt" ] ; then
	    echo "*****************************"
	    cat "DEACTIVATED.txt"
	    echo "*****************************"
	fi
	
	exitval=0
	break
    else
	echo "  'ant $cmd' unrecognised in `pwd` folder for extension $extension"
	exitval=3
	continue
    fi
done
popd > /dev/null

if [ "$exitval" != "0" ] ; then
    echo "Deactivate failed: None of the ant deactivation commands were recognised"
    exit $exitval
fi

# else deactivation success:
echo "Marking the deactivated extension folder inactive: $extension.inactive"
mv $extension "$extension.inactive"

if [ "x$ORIG_GSDL3SRCHOME" != "x" ] ; then
    echo ""
    echo "The extension $extension has been deactivated."
    echo ""
    echo "It appears you had sourced gs3-setup, so you'll want to open a new terminal"
    echo "and source it again to take the deactivation into account."
    echo ""
fi

exit 0
