#! /bin/bash
# (c) by hajtech
# Author ppatzelt@haj.tech

# EXAMPLE for POST-Deploy
# Sysctl Service
#
# install and remove sysctl services
#
# if [[ -d ${BASE_PATH}/cfg/srv/sysctl ]]; then
#     for FILE in ${BASE_PATH}/cfg/srv/sysctl/*.service ; do
#         SERVICE=`basename ${FILE}`
#         SERVICE_NAME=`basename ${SERVICE} .service`
#         if [[ ! -f /etc/systemd/system/${SERVICE} ]]; then
#             echo "Installing service ${SERVICE}:"
#             sudo /usr/local/bin/sysctl_service_add ${BASE_PATH}/cfg/srv/sysctl/${SERVICE}
#         else
#             if cmp --silent /etc/systemd/system/${SERVICE} ${BASE_PATH}/cfg/srv/sysctl/${SERVICE} ; then
#                 echo "Restarting service ${SERVICE}:"
#                 sudo /usr/sbin/service ${SERVICE_NAME} restart
#             else
#                 echo "Re-Installing service ${SERVICE}:"
#                 sudo /usr/local/bin/sysctl_service_del ${BASE_PATH}/cfg/srv/sysctl/${SERVICE}
#                 sudo /usr/local/bin/sysctl_service_add ${BASE_PATH}/cfg/srv/sysctl/${SERVICE}
#             fi
#         fi
#     done
# fi
#
# EXAMPLE SERVICE-Template
# [Unit]
# Description=Servicename

# [Service]
# Type=simple
# ExecStart=/bin/examplecommand --param1 /moep
# Restart=on-failure
# User=root
# RestartSec=3
# PIDFile=/tmp/socat.pid

# [Install]
# WantedBy=multi-user.target


# 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 script is missing. Aborting."
    exit 1
fi

ORIGIN=$1
BASENAME=`basename $ORIGIN`
TARGET_DIR="/etc/systemd/system"

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

if [[ ! ${BASENAME} == *.service ]]; then
    echo "  Service files must be extended by .service, eg. websocket.service - 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}

systemctl daemon-reload
systemctl start ${BASENAME}

sleep 3

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