#!/bin/bash

# Copy this script to the VM where you want to provision a Greenstone install

sudo apt-get -y update

sudo apt-get -y install wget subversion

#sudo apt install software-properties-common
#sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt-get -y install ansible


echo "Getting latest version of DOWNLOAD-GS3-PLAYBOOKS.sh"
wget -O DOWNLOAD-GS3-PLAYBOOKS.sh https://trac.greenstone.org/browser/main/trunk/greenstone3/src/ansible-playbooks/DOWNLOAD-GS3-PLAYBOOKS.sh?format=txt

chmod +x DOWNLOAD-GS3-PLAYBOOKS.sh
./DOWNLOAD-GS3-PLAYBOOKS.sh

if [ -d gs3-ansible-playbooks ] ; then
    # Note, the backslashes are using in the following to prevent (lexically fool)
    # the 'cat | sed express' (that is turning this .sh.in file
    # into .sh) from performing the substitute work on the backslashed versions

    echo "Transforming gs3-ansible-playbooks/vars/default-core.yml for use by gcloud scripts"
    echo "  #UNCOMMENT-IF-GCLOUD#"
    echo "  #COMMENT-OUT-IF-GCLOUD#"
    
    sed -i \
	-e "s/@GSVM\_USER@/@GSVM_USER@/g" \
	-e "s/@GSVM\_INSTANCE@/@GSVM_INSTANCE@/g" \
	-e "s/@GSVM\_TL\_DOMAIN@/@GSVM_TL_DOMAIN@/g" \
	-e "s/@GSVM\_FQDN@/@GSVM_FQDN@/g" \
	gs3-ansible-playbooks/vars/default-core.yml
	
    sed -i \
	-e 's/#UNCOMMENT-IF-GCLOUD#//' \
	-e 's/^\(.*\)#COMMENT-OUT-IF-GCLOUD#\(.*\)$/## \1#REVERT-NEXT-TWO-LINES-IF-NOT-GCLOUD#\2/' \
	gs3-ansible-playbooks/vars/default-core.yml    
fi

cd gs3-ansible-playbooks/ \
    && ./01-RUN-ANSIBLE-BASE-INSTALL.sh @GSVM_USER@ \
    && ./02-RUN-ANSIBLE-REVPROXY.sh @GSVM_USER@

if [ $? = 0 ] ; then
    # An improvement would be to determine gsdl3srchome from vars/default-core.yml
    # and use that.
    cd ..
    cd greenstone3-svn
    ./ant-start-with-exts.sh

    if [ $? = 0 ] ; then
	echo ""
	echo "===="
	echo "= https://@GSVM_FQDN@/greenstone3/library"
	echo "===="
	echo ""
    else
	echo "" >&2
	echo "!!!!" >&2
	echo "! An error occurred in starting the Greenstone3 DL server" >&2
	echo "!!!!" >&2
	echo "" >&2	
    fi
    
else
    echo "" >&2
    echo "!!!!" >&2
    echo "! An error occurred in running the ansible playbooks" >&2
    echo "! The Greenstone3 Tomcat server has *not* been started" >&2
    echo "!!!!" >&2
    echo "" >&2
fi
    
