#!/bin/bash

# Run this script with optional args:
# This script can be run with 0, 1, or 2 arguments
# 0 args - service-user defaults to 'www-data' and the service-name defaults 'greenstone3
# 1 arg  - command-line argument is the service-name, and the service-user defaults 'www-data'
# 2 args - first command-line argument is the service-user; and the second is the service-name

help_arg=0
if [ $# = 1 ] && [ $1 = "-?" ] ; then
    help_arg=1
elif [ $# = 1 ] && [ $1 = "-h" ] ; then
    help_arg=1
elif [ $# = 1 ] && [ $1 = "-help" ] ; then
    help_arg=1
elif [ $# = 1 ] && [ $1 = "--help" ] ; then
    help_arg=1
fi

if [ $help_arg = "1" ] || [ $# -ge 3 ] ; then
    # Usage then stop
    echo "" >&2
    echo "----" >&2
    echo "Usage:" >&2
    echo "  $0 service-name service-user" >&2
    echo "  $0 service-name" >&2
    echo "  $0" >&2
    echo "  (service-name defaults to 'greenstone3' and service-user defaults to 'www-data')" >&2
    echo "" >&2
    echo "For example, to install the 'greenstone3' service running as www-data:" >&2
    echo "    $0 greenstone3" >&2
    echo "----" >&2

    exit 0
    
elif [ $# = 1 ] ; then
    # Assume username for service is 'www-data'    
    gsdl_service_name=$1 
    gsdl_service_username="www-data"
else
    gsdl_service_name=$1
    gsdl_service_username=$2
fi


if [ -d "/etc/systemd/system/" ] ; then

    if [ "x$GSDL3SRCHOME" = "x" ] ; then

	full_progdir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null && pwd )"
	cd "$full_progdir"
	
	cd .. && source ./gs3-setup.sh && cd service.d
    fi
    echo ""
    
    echo "****"
    echo "* Generating $gsdl_service_name.service from greenstone3.service.in"
    echo "* using user $gsdl_service_username"
    echo "****"
    cat greenstone3.service.in \
	| sed "s%@GSDL3SRCHOME@%$GSDL3SRCHOME%g" \
	| sed "s%@GSDL_SERVICE_USERNAME@%$gsdl_service_username%g" \
	      > $gsdl_service_name.service
     
    echo "****"
    echo "* Copying $gsdl_service_name.service to /etc/systemd/system/"
    echo "****"
    sudo /bin/cp $gsdl_service_name.service /etc/systemd/system/.

    echo ""
    echo "----"
    echo "General info:"
    echo "  In the event of the service being updated, you will most likely need to run:"
    echo "    sudo systemctl daemon-reload"
    echo ""
    echo "  To enable this service to be run at boot-up time, run:"
    echo "    sudo systemctl enable $gsdl_service_name"
    echo "----"
    
else
    echo "Error: Failed to find '/etc/systemd/system'" >&2
    echo "This install script was developed on a Debian system." >&2
    echo "It looks like your Linux Distribution uses a different directory structure for services" >&2

    exit 1
fi  

