#!/bin/bash

# With a nod to the paradox that this file is currently committed
# to the very svn repository that we're looking to svn checkout from ...

checkout_dir="${1:-greenstone3-svn}"

echo ""
echo "Assumptions:"
echo "  1. You have 'svn' installed"
echo "  2. You have 'wget' installed"
echo ""
echo ["Pausing for 3 seconds]"
sleep 3


if [ ! -d "$checkout_dir" ] ; then
    svn co https://svn.greenstone.org/main/trunk/greenstone3 "$checkout_dir"
    checkout_status=$?
else
    echo "Detected existing directory '$checkout_dir' -- skipping svn checkout"
    checkout_status=0
fi

if [ $checkout_status = 0 ] ; then
    cd "$checkout_dir"
    cd ext-cli

    if [ ! -d selfcontained-jdk ] ; then
	./get-selfcontained-jdk.sh
    fi

    if [ ! -d selfcontained-ant ] ; then
	./get-selfcontained-ant.sh
    fi

    if [ ! -d selfcontained-perl-with-cpan ] ; then
        ./get-selfcontained-perl-with-cpan.sh
    fi
    
    if [ ! -d selfcontained-python3 ] ; then
	./get-selfcontained-python3.sh
    fi

    cd ..

    if [ $? = 0 ] ; then
	echo ""
	echo "Away to compile up Greenstone3"
	echo "This might take a while"
	echo ""
	echo "[Pausing for 3 seconds]"
	sleep 3

	# Force fresh sourcing of setup file
	export GSDL3SRCHOME=
	export GSDLHOME=
	source ./gs3-setup.sh

	# Compile up with default settings
	ant && echo "y" | ant prepare && ant install

	if [ $? = 0 ] ; then
	   echo ""	
	   echo "****"
	   echo "* Greenstone3 successfully installed with default settings!"
	   echo "*"
	   echo "* To start your Greenstone3 server run:"
	   echo "*   cd \"$checkout_dir\""
	   echo "*   ./ant-start-with-exts.sh"
	   echo "*"
	   echo "* You can then visit the installed DL in your browser via:"
	   echo "*   http://localhost:8383/greenstone3/library"
	   echo "****"
	   echo ""
	fi
    fi
else
    echo "" >&2
    echo "An error was enountered checking out Greenstone3 from svn" >&2
    echo "Enable to find '$checkout_dir'. Do you have 'svn' installed?" >&2    
fi

