#!/bin/sh
#
# Adds or deletes sflowtrend-server as a service to start on boot. The
# service init.d script is assumed to have been previously created. If possible the
# service is registered for automatically starting in /etc/rc?.d. chkconfig
# is tried for this, and if this doesn't exist then update-rc.d will be tried.
# If neither exists, then the service is not registered to start automatically.
# In this case, the sflowtrend-server service should be added to the boot time
# services in the appropriate way for the current distribution.
#
# If the system uses systemd, no action is required to register the service.
#
# Parameters:
# $1 --add|--del to add or delete the service
# $2 the service executeable
# $3 the name of the service to install

set -e

usage()
{
    echo "$0: usage: $0 --add service-executable service-name | --del service-name"
}

#
# Adds a service.
#  $1: the service executable
#  $2: the name of the service to add
#
add()
{
    service=$1
    serviceName=$2
    # Auto-start the service via chkconfig or update-rc.d, as available
    if [ ${chkconfig} ]
    then
        chkconfig --add ${serviceName} > /dev/null 2>&1
    elif [ ${updatercd} ]
    then
        # Extract the S and K values from the service
        chkconfigDef=`grep chkconfig: ${service}`
        kValue=${chkconfigDef##*chkconfig:* }
        chkconfigDef=${chkconfigDef% *}
        sValue=${chkconfigDef##*chkconfig:* }
        update-rc.d ${serviceName} defaults ${sValue} ${kValue} > /dev/null 2>&1
    fi
}

#
# Deletes a service.
#  $1: the name of the service to delete
#
delete()
{
    serviceName=$1
    if [ ${chkconfig} ]
    then
        chkconfig --del ${serviceName} > /dev/null 2>&1
    elif [ ${updatercd} ]
    then
        update-rc.d ${serviceName} remove > /dev/null 2>&1
    fi
}

# Determine which of (if any) systemctl, chkconfig or update-rc.d is available
if command -v systemctl > /dev/null 2>&1
then
    exit  # Don't need to do anything with systemctl
elif command -v chkconfig > /dev/null 2>&1
then
    chkconfig=true
elif command -v update-rc.d > /dev/null 2>&1
then
    updatercd=true
fi

mode=$1

if [ "${mode}" = "--add" ]
then
    if [ $# -eq 3 ]
    then
        add $2 $3
    else
        usage
        exit 3
    fi
elif [ "${mode}" = "--del" ]
then
   if [ $# -eq 2 ]
   then
       delete $2
   else
       usage
       exit 3
   fi
else
    usage
fi
