#!/usr/bin/env bash

set -o pipefail  # trace ERR through pipes
set -o errtrace  # trace ERR through 'time command' and other functions
set -o nounset   ## set -u : exit the script if you try to use an uninitialised variable
set -o errexit   ## set -e : exit the script if any statement returns a non-true return value

if [[ "$#" -le 1 ]]; then
    echo "Usage: $0 <command> <service>"
    exit 1
fi

SERVICE_COMMAND=$1
shift

for SERVICE in "$@"; do
    RUN_FILE="/opt/docker/bin/service.d/${SERVICE}.sh"
    SERVICE_FILE="/opt/docker/etc/supervisor.d/${SERVICE}.conf"
    PROVISION_FILE="/opt/docker/provision/service.d/${SERVICE}.sh"

    case "$SERVICE_COMMAND" in
        enable)
            # Run on demand installation/provisioning
            if [[ -f "$PROVISION_FILE" ]]; then
                echo "Running provisioning for ${SERVICE}, please wait..."

                ## execute scripts
                . "$PROVISION_FILE"

                ## remove directory (one run time)
                rm -f -- "$PROVISION_FILE"
            fi

            ## Enable service
            if [[ -f "$SERVICE_FILE" ]]; then
                go-replace --mode=lineinfile \
                    -s 'autostart =' -r 'autostart = true' \
                    -- "$SERVICE_FILE"
            else
                echo "[ERROR] Service '${SERVICE}' not found (tried ${SERVICE_FILE})"
                exit 1
            fi
            ;;

        disable)
            ## Disable service
            if [[ -f "$SERVICE_FILE" ]]; then
                go-replace --mode=lineinfile \
                    -s 'autostart =' -r 'autostart = false' \
                    -- "$SERVICE_FILE"
            else
                echo "[ERROR] Service '${SERVICE}' not found (tried ${SERVICE_FILE})"
                exit 1
            fi
            ;;

        install)
            # Run on demand installation/provisioning
            if [[ -f "$PROVISION_FILE" ]]; then
                echo "Running provisioning for ${SERVICE}, please wait..."

                ## execute scripts
                . "$PROVISION_FILE"

                ## remove directory (one run time)
                rm -f -- "$PROVISION_FILE"
            fi
            ;;

        run)
            if [[ -f "$RUN_FILE" ]]; then
                exec "$RUN_FILE"
            else
                echo "[ERROR] Service '${SERVICE}' not found (tried ${RUN_FILE})"
                exit 1
            fi
            ;;

        stop|start|restart|status|pid|check)
            service "${SERVICE}" "$SERVICE_COMMAND"
            ;;

         *)
            echo "[ERROR] $SERVICE_COMMAND is not a valid command"
            exit 1
            ;;
    esac
done

