#! /bin/bash
# (c) by ennit interactive GmbH, 2015
# Author jbradler@ennit.com

# EXAMPLE for POST-Deploy
# Service
#
# install and remove services (init.d)
#
# if [[ -d ${BASE_PATH}/cfg/srv/init.d ]]; then
#     for FILE in ${BASE_PATH}/cfg/srv/init.d/* ; do
#         SERVICE=`basename ${FILE}`
#         if [[ ! -f /etc/init.d/${SERVICE} ]]; then
#             echo "Installing service ${SERVICE}:"
#             sudo /usr/local/bin/service_add ${BASE_PATH}/cfg/srv/init.d/${SERVICE}
#         else
#             if cmp --silent /etc/init.d/${SERVICE} ${BASE_PATH}/cfg/srv/init.d/${SERVICE} ; then
#                 echo "Restarting service ${SERVICE}:"
#                 sudo /usr/sbin/service ${SERVICE} restart
#             else
#                 echo "Re-Installing service ${SERVICE}:"
#                 sudo /usr/local/bin/service_del ${BASE_PATH}/cfg/srv/init.d/${SERVICE}
#                 sudo /usr/local/bin/service_add ${BASE_PATH}/cfg/srv/init.d/${SERVICE}
#             fi
#         fi
#     done
# fi

# Include defaults if available
if [ -f /etc/default/hosting-tools ]; then
    . /etc/default/hosting-tools
fi

if [[ $# -eq 0 ]] ; then
    echo "Missing argument. Source file name for service start script is missing. Aborting."
    exit 1
fi

ORIGIN=$1
BASENAME=`basename $ORIGIN`
TARGET_DIR="/etc/init.d"

if [ ! -f $ORIGIN ] || [ "" == "${BASENAME}" ]; then
    echo "  Could not find service start script $ORIGIN - Aborting."
    exit 1
fi

if [ -f "${TARGET_DIR}/${BASENAME}" ]; then
    echo "  Service ${BASENAME} has been installed already. Aborting."
    exit 1
fi

cp -f ${ORIGIN} ${TARGET_DIR}/${BASENAME} 2> /dev/null
chmod 755 ${TARGET_DIR}/${BASENAME}
chown root:root ${TARGET_DIR}/${BASENAME}

update-rc.d ${BASENAME} defaults
update-rc.d ${BASENAME} enable

service ${BASENAME} start

sleep 1

if [ $? -eq 0 ]; then
    exit 0
else
    echo "  Could not copy service start script ..."
    echo "  from ${ORIGIN} to ${TARGET_DIR}/${BASENAME}"
    exit 1
fi