#!/bin/sh
#
#	Install files to remote server using FIP
#
dir=`dirname $0`
cd $dir

# Don't show Gradle status message on every line
# (this prevents non-terminal output repeating the status a hundred times)
export TERM=dumb

# Make sure we don't run out of memory
export JAVA_OPTS=" -Xms256m -Xmx2g -XX:MaxPermSize=512m"
#echo JAVA_OPTS set to \"${JAVA_OPTS}\"


#
#	Wait until the server is running
#
echo "Checking fipserver is running on remote server."
n=1
while ! curl -s http://{{&HOST}}:{{&FIP_PORT}}/status?root={{&serverHome}} ; do	
	n=`expr $n + 1`
	if [ $n -gt 24 ] ; then
		echo ''
		echo 'Error: Timeout waiting for FIP server to run on Docker container.'
		echo 'Installation aborted.'
		echo ''
		exit 1
	fi
	echo waiting
	sleep 5
done
echo "ok, it's running."

# Use a temporary file for output. This is required because this script
# is called from Grunt, which dies if it receives too many lines of output.
tmpfile=/tmp/install-output-$$

# Use Gradle to build run InstallUtil
echo "$ cd" `pwd`
echo "$ ./gradlew"
echo "please wait (buffering output to ${tmpfile})"
./gradlew 2>&1 > ${tmpfile}
rv=$?


#
#	See if there was an error
#
if [ "${rv}" == "0" ] ; then
        #
		#		No error.
        #       Displaying too much output causes Grunt to have problems
        #
        lines=$(wc -l ${tmpfile}  | sed 's/[ ]*\([0-9]*\) \/.*/\1/')
        if [ "${lines}" -le 80 ] ; then
                # Not many lines - show them all
                cat ${tmpfile}
        else
                # Only show just the top and the bottom
                head -45 ${tmpfile}
                echo ""
                echo "        ...   [shortened from ${lines} lines]"
                echo ""
                tail -30 ${tmpfile}
        fi
else
        # Had an error - display the entire output
        cat ${tmpfile}
fi

#echo "do_install/DOIT: grunt exit status is ${rv}"
#echo Exited with code $rv
# Anything else?
# ...

# Exit now
exit $rv
