#!/bin/bash

storedir="`pwd`"
thisdir="`dirname \"$0\"`"
thisdir="`cd \"$thisdir\" && pwd`"
cd "$thisdir"
source setup.bash

testdone=0

cgibin="cgi-bin"
if [ -d "cgi-bin/$GSDLOS$GSDLARCH" ] ; then
  cgibin="cgi-bin/$GSDLOS$GSDLARCH"
fi


function test-gsdlhome {
    if [ $testdone == "0" ] ; then
        if test -z "$GSDLHOME" ; then
	    echo "" ;
  	    echo "Environment variable GSDLHOME not set." ;
	    echo "  This needs to be set to run this gsicontrol command." ;
	    echo "  Have you run 'source setup.bash'?" ;
	    echo "" ;
	    exit 1
        else
	    echo "Using: " ;
	    echo "  GSDLHOME = $GSDLHOME" ;
	    echo "  GSDLOS   = $GSDLOS" ; 
        fi
	testdone=1
    fi
}  

function configure-cgi {
    test-gsdlhome
    if test ! -e "$GSDLHOME/$cgibin/gsdlsite.cfg" ; then
	echo "Configuring $cgibin/gsdlsite.cfg" ;
	echo "# **** This file is automatically generated, do not edit ****" > "$cgibin/gsdlsite.cfg" ;
	echo "# For local customization of Greenstone, edit gsdlsite.cfg.in" >> "$cgibin/gsdlsite.cfg" ;
	echo "" >> "$cgibin/gsdlsite.cfg" ;
	sed "s@\*\*GSDLHOME\*\*@$GSDLHOME@g" "$cgibin/gsdlsite.cfg.in" >> "$cgibin/gsdlsite.cfg" ;
    else
	echo "WARNING: Nothing done for make configure-cgi." ;
	echo "   If you wish to regenerate the file " ;
	echo "   $GSDLHOME/$cgibin/gsdlsite.cfg" ;
	echo "   from scratch, delete the existing file first." ;
    fi
}

function configure-admin {
    test-gsdlhome
    echo "" ;
    echo "Configuring admin user password:" ;
    encrypted_password=`getpw` ;
    if [ $? = "0" ] ; then
	echo -e "[admin]\n<enabled>true\n<groups>administrator,colbuilder,all-collections-editor\n<password>$encrypted_password\n<username>admin" \
	    | txt2db -append "$GSDLHOME/etc/users.gdb" ;
    else
	echo "Did not set password" ;
    fi
    echo ""
}


function configure-port-and-connection {
    test-gsdlhome

    echo "Enter port number to use:"
    read port ;
    echo "Enter host IP to allow (127.0.0.1 is included by default):"
    read hostIP ;
	echo "Enter hostname or list of hosts to allow (localhost included by default):"
    read hosts ;
    echo "Allow external connections [yes/no]:"
    read connection ;    
    if [ "x$connection" = "xyes" ] || [ "x$connection" = "xy" ] ; then
        allowfromall="Allow"
    else
        allowfromall="Deny"
    fi

    lib_path_var="LD_LIBRARY_PATH" ;
    if [ $GSDLOS = "darwin" ] ; then
	lib_path_var="DYLD_LIBRARY_PATH"
    fi

    if test -e "$GSDLHOME/$cgibin/gsdlsite.cfg" ; then
	collecthome=`egrep "^collecthome" "$GSDLHOME/$cgibin/gsdlsite.cfg" | awk '{print $2}'` ;
    fi
    if test -z $collecthome ; then
	collecthome="$GSDLHOME/collect" ;
    fi

    if test ! -z $port ; then
	echo "Port: $port" ;
# if called by reset-gsdlhome, then httpd.conf file was regenerated by install-bindist.sh script and
# contains placeholder strings, including for Listen port. So can't stop web-server in such a case.
	if test -e "$GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/conf/httpd.conf" ; then
	    confport=`egrep "^Listen" $GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/conf/httpd.conf | awk '{print $2}'` ;
	    if [ "$confport" != "**PORT**" ] ; then 
		echo "Stopping web server (if running)" ;
		web-stop-tested ;
	    fi
	fi
	echo "Setting config file to use port $port";
# Need to remove extra quotes around $collecthome. ${string//abc/xyz} does a replace all on abc with xyz
	cat "$GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/conf/httpd.conf.in" \
	| sed "s@\*\*GSDL_OS_ARCH\*\*@$GSDLOS$GSDLARCH@g" \
	| sed "s@\*\*PORT\*\*@$port@g" \
	| sed "s@\*\*CONNECTPERMISSION\*\*@$allowfromall@g" \
	| sed "s@\*\*HOST_IP\*\*@$hostIP@g" \
	| sed "s@\*\*HOSTS\*\*@$hosts@g" \
	| sed "s@\*\*COLLECTHOME\*\*@${collecthome//\"/}@g" \
	| sed "s@\*\*GSDLHOME\*\*@$GSDLHOME@g" \
	| sed "s@\*\*APACHE_HOME_OS\*\*@$GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH@g" \
	| sed "s@\*\*LIBRARY_PATH_VAR\*\*@$lib_path_var@g" \
	> "$GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/conf/httpd.conf" ;
	echo "Type '$0 web-start' to start the web server running on port $port" ;
    fi ;
    echo "Done" ;
}


MONITOR_SUCCESS="MAKE SUCCESSFUL"
MONITOR_FAILED="MAKE FAILED"
MONITOR_FINISHED="MAKE DONE"

function configure-apache {
    test-gsdlhome
    configfile=$1 ;
# if no configfile given, launch it with llssite.cfg. Create it from the template if needed.
    if [ "x$configfile" = "x" ]; then
	if test ! -e "$GSDLHOME/llssite.cfg" && test -e "$GSDLHOME/llssite.cfg.in" ; then
	    cp "$GSDLHOME/llssite.cfg.in" "$GSDLHOME/llssite.cfg" ;
	fi
	configfile="$GSDLHOME/llssite.cfg";
    fi ;
    echo "Configuring the apache webserver..." ;
    port=`egrep "^portnumber" $configfile | awk -F= '{print $2}'` ;
    hostIP=`egrep "^hostIP" $configfile | awk -F= '{print $2}'` ;
    hosts=`egrep "^hosts" $configfile | awk -F= '{print $2}'` ;    
    
    externalaccess=`egrep "^externalaccess" $configfile | awk -F= '{print $2}'` ;
    if [ "x$externalaccess" = "x1" ] ; then 
	externalaccess="yes"
    else
	externalaccess="no"
    fi

    echo -e "$port\n$hostIP\n$hosts\n$externalaccess" | configure-port-and-connection ;
    if test -e "$GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/conf/httpd.conf" ; then
	echo $MONITOR_SUCCESS;
    else
	echo $MONITOR_FAILED;
    fi
    echo $MONITOR_FINISHED
}

function configure-web {
    for one_file in gs2-server.app gli.app client-gli.app gems.app ; do 	
	if test -e "$one_file/Contents/document.wflow.in" ; then
	    if test ! -e "$one_file/Contents/document.wflow" ; then
		sed "s@\*\*GSDLHOME\*\*@$GSDLHOME@g" "$one_file/Contents/document.wflow.in" > "$one_file/Contents/document.wflow"
	    fi
	fi
    done ;

    configure-cgi
    configure-apache $1
}

# Forces configure-cgi by renaming gsdlsite.cfg
# but only if we actually *need* to relocate gsdlhome.
# We relocate at all times, except when there is a gsdlsite.cfg file with its
# gsdlhome property the same as the current (greenstone installation) directory
function reset-gsdlhome {
    echo "" ;
    relocate=yes ;

# don't just update gsdlsite.cfg, but also the path to perl at the top of gliserver.pl and the other cgi-bin perl files
# if this is a perl included with the Greenstone distribution
    if test -e "$GSDLHOME/$cgibin/gsdlsite.cfg" ; then
	stored_gsdlhome=`egrep "^gsdlhome" "$cgibin/gsdlsite.cfg" | awk '{print $2}'` ;
	if [ "x$stored_gsdlhome" != "x$GSDLHOME" ]; then
	    /bin/mv "$GSDLHOME/$cgibin/gsdlsite.cfg" "$GSDLHOME/$cgibin/gsdlsite.cfg.bak" ;
	    echo "**** Regenerating $GSDLHOME/$cgibin/gsdlsite.cfg" ;
	    echo "**** Previous version of file now $GSDLHOME/$cgibin/gsdlsite.cfg.bak" ;

	    if test -d "$GSDLHOME/bin/$GSDLOS/perl" ; then
		gliserverfile=$GSDLHOME/$cgibin/gliserver.pl ;
		/bin/cp "$gliserverfile" "$gliserverfile.bak" ;	    
		sed "s@$stored_gsdlhome@$GSDLHOME@g" "$gliserverfile.bak" > "$gliserverfile" ;
		rm -f "$gliserverfile.bak" ;

		metaserverfile=$GSDLHOME/$cgibin/metadata-server.pl ;
		/bin/cp "$metaserverfile" "$metaserverfile.bak" ;	    
		sed "s@$stored_gsdlhome@$GSDLHOME@g" "$metaserverfile.bak" > "$metaserverfile" ;
		rm -f "$metaserverfile.bak" ;

		checksumfile=$GSDLHOME/$cgibin/checksum.pl ;
		/bin/cp "$checksumfile" "$checksumfile.bak" ;	    
		sed "s@$stored_gsdlhome@$GSDLHOME@g" "$checksumfile.bak" > "$checksumfile" ;
		rm -f "$checksumfile.bak" ;
	    fi

	else
	    relocate=
	fi
    fi	
    
    if [ "x$relocate" = "xyes" ]; then
	apache_home_os="$GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH"
	
	if test ! -e "$apache_home_os/bin/apachectl.in" ; then
	    make apache-for-dist
	fi
	
	replace_list="conf/extra/httpd-dav.conf \
	        conf/extra/httpd-manual.conf \
	        conf/extra/httpd-autoindex.conf \
	        conf/extra/httpd-vhosts.conf \
	        conf/extra/httpd-ssl.conf \
	        conf/extra/httpd-multilang-errordoc.conf \
	        conf/original/extra/httpd-dav.conf \
	        conf/original/extra/httpd-manual.conf \
	        conf/original/extra/httpd-autoindex.conf \
	        conf/original/extra/httpd-vhosts.conf \
	        conf/original/extra/httpd-ssl.conf \
	        conf/original/extra/httpd-multilang-errordoc.conf \
	        conf/original/httpd.conf\
	        lib/apr-util-1/apr_dbd_odbc.la \
	        lib/apr-util-1/apr_dbd_sqlite3.la \
	        lib/pkgconfig/apr-util-1.pc \
	        lib/pkgconfig/apr-1.pc \
	        lib/libaprutil-1.la \
	        lib/libapr-1.la \
	        build/config_vars.mk \
	        build/config.nice \
	        build/apr_rules.mk \
	        bin/dbmmanage \
	        bin/apu-1-config \
	        bin/apr-1-config \
	        include/ap_config_auto.h \
	        include/ap_config_layout.h"

	for one_file in apachectl envvars envvars-std ; do 
	    /bin/cp "$apache_home_os/bin/$one_file.in" "$apache_home_os/bin/$one_file"
	done 
	
	for one_file in $replace_list ; do 
	    /bin/cp "$apache_home_os/$one_file.in" "$apache_home_os/$one_file"
	done
	
	/bin/cp "$apache_home_os/bin/apr-1-config.in" "$apache_home_os/bin/apr-1-config"
	
	/bin/cp "$apache_home_os/bin/apu-1-config.in" "$apache_home_os/bin/apu-1-config"
	
	/bin/cp "$apache_home_os/build/config_vars.mk.in" "$apache_home_os/build/config_vars.mk"
	
# replace template files with active versions. The following will generate a httpd.conf
# file with placeholder strings, all of which we'll replace shortly hereafter.
	bash "$apache_home_os/install-bindist.sh" "$apache_home_os"
	
	log4jprop=$GSDLHOME/lib/java/log4j.properties
	sed "s^@gsdl2home@^$GSDLHOME^g" "$log4jprop.in" > "$log4jprop"
	
	for one_file in gs2-server.app gli.app client-gli.app gems.app ; do 
	    if test -e "$one_file/Contents/document.wflow" ; then
		rm -f "$one_file/Contents/document.wflow"
	    fi
	done
	
	configure-web $1
    fi
}

function web-status {
    test-gsdlhome
    $GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/bin/apachectl status
}

function web-start { 
    test-gsdlhome
    $GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/bin/apachectl start
    if [ $? = 0 ] ; then
	echo $MONITOR_SUCCESS;
    else
	echo $MONITOR_FAILED;
    fi
    echo $MONITOR_FINISHED;
}

function web-restart {
    test-gsdlhome
    $GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/bin/apachectl restart
    if [ $? = 0 ] ; then
	echo $MONITOR_SUCCESS;
    else
	echo $MONITOR_FAILED;
    fi
    echo $MONITOR_FINISHED;
}

function web-graceful {
    test-gsdlhome
    $GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/bin/apachectl graceful
    if [ $? = 0 ] ; then
	echo $MONITOR_SUCCESS;
    else
	echo $MONITOR_FAILED;
    fi
    echo $MONITOR_FINISHED;
}

function web-stop-tested {
# This version runs without testing for GSDLHOME
# Useful to be run as a target when we know test-gsdlhome has already
# been done.  This avoids an unnecessary repetition of printing
# out the values of GSDLHOME and GSDLOS
    if test -e "$GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/conf/httpd.conf" ; then
	$GSDLHOME/apache-httpd/$GSDLOS$GSDLARCH/bin/apachectl stop ;
    fi
}

function web-stop {
    test-gsdlhome
    web-stop-tested
    if [ $? = 0 ] ; then
	echo $MONITOR_SUCCESS;
    else
	echo $MONITOR_FAILED;
    fi
    echo $MONITOR_FINISHED;
}

function usage {
    echo ""
    echo "   Usage: $0 <command>"
    echo "          where <command> is any of the following: "
    echo "   web-start"
    echo "   web-stop"
    echo "   web-restart"
    echo "   web-status"
    echo "   web-graceful"
    echo "   configure-admin"
    echo "   configure-web [config-filename]"
    echo "   configure-apache [config-filename]"
    echo "   configure-cgi"
    echo "   set-port"
    echo "   reset-gsdlhome [config-filename]"
    echo "        (Save a copy of $cgibin/gsdlsite.cfg to preserve any customisations)"
    echo "   test-gsdlhome"
    echo "   web-stop-tested"
    echo ""
    echo "   NOTES: if config-filename not specified, $GSDLHOME/llssite.cfg will be used"
}


if [[ $# < 1  || $# > 2 ]] ; then
    usage
    exit 0
fi

target=$1
configfile=$2

# remove any extraneous double quotes
configfile=${configfile//\"/}

# if there's a libiconv.dylib in gnome-lib-mimimal's lib folder, then apache-httpd would have been compiled dependent on it
# in such a case, need to add it to the (DY)LD_LIBRARY_PATH. This happens with Mac Lion, may happen with andropid.
if [ -f $GSDLHOME/ext/gnome-lib-minimal/$GSDLOS/lib/libiconv.dylib ] || [ -f $GSDLHOME/ext/gnome-lib/$GSDLOS/lib/libiconv.dylib ] ; then
    if [ $GSDLOS = "darwin" ] ; then
	DYLD_LIBRARY_PATH=$GSDLHOME/ext/gnome-lib-minimal/$GSDLOS/lib:$DYLD_LIBRARY_PATH
        # DYLD_FALLBACK_LIB_PATH doesn't work with apache-httpd:
	#DYLD_FALLBACK_LIBRARY_PATH=$GSDLHOME/ext/gnome-lib-minimal/$GSDLOS/lib:$DYLD_FALLBACK_LIBRARY_PATH
    elif [ $GSDLOS = "linux" ] ; then
	LD_LIBRARY_PATH=$GSDLHOME/ext/gnome-lib-minimal/$GSDLOS/lib:$LD_LIBRARY_PATH
    fi
fi

case $target in
    web-start)
	web-start;;
    web-stop)
	web-stop;;
    web-restart)
	web-restart;;
    web-status)
	web-status;;
    web-graceful)
	web-graceful;;
    configure-admin)
	configure-admin;;
    configure-web)
	configure-web $configfile;;
    configure-apache)
	configure-apache $configfile;;
    configure-cgi)
	configure-cgi;;
    set-port)
	configure-port-and-connection;;
    reset-gsdlhome)
	reset-gsdlhome;;
    test-gsdlhome)
	test-gsdlhome;;
    web-stop-tested)
	web-stop-tested;;
    *)
	echo
        echo "Command unrecognised: $target"
	usage;;

esac

# jump back to directory we originally got called from
cd "$storedir"
exit;
