#!/bin/bash

OS_ALLCAPS=`uname -s | sed 's/_.*$//' | tr 'a-z' 'A-Z'`

cli_svn_root=https://svn.greenstone.org/main/trunk/cli-extensions
selfcon_ext=selfcontained-perl-with-cpan


true_bitness=`getconf LONG_BIT`
#installed_dir=${selfcon_ext}/gsperl5-with-cpan-linux64
#if [ "$true_bitness" = "32" ]; then
#    installed_dir=${selfcon_ext}/gsperl5-with-cpan-linux32
#fi
thisOS=`uname -s`
# Above returns "Linux" on linux. To lowercase achieved by:
#https://stackoverflow.com/questions/11392189/how-can-i-convert-a-string-from-uppercase-to-lowercase-in-bash
thisOS=$(echo "$thisOS" | tr '[:upper:]' '[:lower:]')

if [ "$thisOS" = "linux" ] ; then
    installed_dir=${selfcon_ext}/gsperl5-with-cpan-linux${true_bitness}
else
    installed_dir=${selfcon_ext}/gsperl5-with-cpan-darwin
fi

echo ""
if [ ! -d $selfcon_ext ] ; then
    echo "Checking out from svn: Greenstone3's $selfcon_ext extension"
    svn co $cli_svn_root/$selfcon_ext/source $selfcon_ext

    if [ $? != 0 ] ; then
	echo "Error encountered checking out: " 1>&2
	echo "    svn co $cli_svn_root/$selfcon_ext/source $selfcon_ext" 1>&2
	exit 1
    fi
else
    echo "Detected directory '$selfcon_ext'"
    echo "=> Taken to mean that the svn check-out command has already been run"
fi

echo ""
if [ ! -d $installed_dir ] ; then
    echo "Running the $selfcon_ext/PREPARE-${OS_ALLCAPS}.sh"

    cd $selfcon_ext && ./PREPARE-${OS_ALLCAPS}.sh

    if [ $? != 0 ] ; then
	echo "Error encountered running: " 1>&2
	echo "        cd $selfcon_ext && ./PREPARE-${OS_ALLCAPS}.sh" 1>&2
	exit 1
    fi
	
else
    echo "Detected directory '$installed_dir'"
    echo "=> Taken to mean that the $selfcon_ext/PREPARE-${OS_ALLCAPS}.sh command has already been run"    
fi


if [ "x$GSPERL_WITH_CPAN_HOME" != "x$PWD/$installed_dir" ] ; then
    echo ""
    echo "To use this installed version of Perl, run "
    echo "    source ./SETUP-CLI.sh "
    echo "in the ext-cli folder."
    echo ""
else
    echo ""
    echo "Detected GSPERL_WITH_CPAN_HOME set to \$PWD/$installed_dir"
    echo "=> Taken to mean that the $selfcon_ext SETUP.sh file has been sourced"
fi

echo ""
