#!/bin/bash
################################################################################
# bounceservice.sh - bounce-anywhere script for service run-on-boot setup
#  This script assumes that the service script is already installed in it's proper
#   location.
#
export thescriptname=`basename $0`
export installlogname=/var/log/cbu-installer.log

################################################################################
#  Requires environment variables:
#   $1 - log message
#   installlogname - log file name
function logmsg
{
  echo "$( date '+%F %H:%M:%S' ) ${thescriptname} $1" >> ${installlogname}
  echo "$1"
}

################################################################################
# Source the service type setup.
#
if [ $# -ne 2 ]; then
  logmsg "ERROR: invalid number of parameters specified" >&2
  exit 1
fi
export tmppath=$1
export servicename=$2
logmsg "bouncing ${servicename} from ${tmppath}"
if [ ! -d ${tmppath}/ ]; then
  logmsg "ERROR: cannot locate path to tar installer: ${tmppath}" >&2
  exit 1
fi
. ${tmppath}/setservicetype.sh ${servicename}
if [ $? -ne 0 ]; then
  logmsg "ERROR: cannot source ${tmppath}/setservicetype.sh" >&2
  exit 1
fi

################################################################################
# Bounce the service on this machine.
#
case ${myplatform} in
  "arch")
    systemctl status ${servicename} > /dev/null 2>&1 && systemctl stop ${servicename}
    systemctl start ${servicename} ;;
  "centos")
    logmsg "bouncing ${servicename} on ${myplatform}"
    #service ${servicename} status > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      logmsg "${servicename} already running so stopping first"
      service ${servicename} stop
    fi
    logmsg "now starting $servicename"
    service ${servicename} start || yesnoresult='not '
    logmsg "${servicename} was ${yesnoresult}started"
    ;;
  "fedora")
    /etc/init.d/${servicename} status > /dev/null 2>&1 && /etc/init.d/${servicename} stop
    /etc/init.d/${servicename} start ;;
  "redhat")
    /etc/init.d/${servicename} status > /dev/null 2>&1 && /etc/init.d/${servicename} stop
    /etc/init.d/${servicename} start ;;
  "debian")
    systemctl daemon-reload
    systemctl status ${servicename} > /dev/null 2>&1 && systemctl stop ${servicename}
    systemctl start ${servicename} ;;
  "ubuntu")
    systemctl status ${servicename} > /dev/null 2>&1 && systemctl stop ${servicename}
    systemctl start ${servicename} ;;
  "gentoo")
    /etc/init.d/${servicename} status > /dev/null 2>&1 && rc-service ${servicename} stop
    rc-service ${servicename} start ;;
  *) logmsg "ERROR: unknown linux flavor" >&2 ;;
esac

