#!/bin/bash

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

extension=$1
inactivedir=$1.inactive

#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 "Activating extension $extension"
if [ ! -d "$inactivedir" ] ; then
    echo "Activate failed: Inactive extension $extension ($inactivedir) does not exist"
    exit 1
fi

if [ ! -f "$inactivedir/build.xml" ] ; then
    echo "Activate failed: No build.xml exists in extension $extension ($inactivedir)"
    exit 2
fi

# rename step
mv "$inactivedir" $extension

pushd "$extension" > /dev/null
exitval=0
for cmd in activate add-extension add-service; do
    
    echo "Attempting to run ant $cmd on the extension $extension..."
    ant $cmd > /dev/null 2>&1
    
    if [ "$?" = "0" ] ; then
     	echo "Finished activating extension $extension"
	
	# print out any helpful information provided by the extension
	# if [ -f "ACTIVATED.txt" ] ; then
	#     echo "*****************************"
	#     cat "ACTIVATED.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 "Activate failed: None of the ant activation commands were recognised"
    echo "  Marking the extension folder inactive again as $inactivedir"
    mv $extension "$inactivedir"
    exit $exitval
fi

if [ "x$ORIG_GSDL3SRCHOME" != "x" ] ; then
    echo ""
    echo "The extension $extension has been activated."
    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 activation into account."
    echo ""
fi

exit 0
