#!/bin/bash


ARGUMENT="$(cat -)"
SERVICE="lwr-isc-script-runner.service"

function get_status() {
    if systemctl is-enabled --quiet "${SERVICE}"; then
        echo "enabled"
    else
        echo "disabled"
    fi
}

function fail() {
    echo "Content-type: text/html"
    echo "Status: ${2:-400}"
    echo ""
    [[ -n "${1}" ]] && echo "${1}"
    exit 0
}

function success() {
    echo "Content-type: text/html"
    echo "Status: 200"
    echo ""
    [[ -n "${1}" ]] && echo "${1}"
    exit 0
}



if [[ ${REQUEST_METHOD} != "POST" ]]; then
    fail " ${REQUEST_METHOD} is not implemented for endpoint!" 501
fi

case "${ARGUMENT}" in
    restart)
        status=$(get_status)
        if [[ "${status}" == "disabled" ]]; then
            fail "Could not restart service. Reason: ${SERVICE} is disabled."
        fi

        if ! err=$(systemctl restart "${SERVICE}" 2>&1); then
            fail "Failed to restart ${SERVICE}. Reason: ${err}"
        fi
        ;;
    enable)
        if ! err=$(systemctl enable "${SERVICE}" 2>&1); then
            fail "Failed to enable ${SERVICE}. Reason: ${err}"
        fi

        if ! err=$(systemctl start "${SERVICE}" 2>&1); then
            fail "Failed to start ${SERVICE}. Reason: ${err}"
        fi
        ;;
    disable)
        if ! err=$(systemctl stop "${SERVICE}" 2>&1); then
            fail "Failed to stop ${SERVICE}. Reason: ${err}"
        fi

        if ! err=$(systemctl disable "${SERVICE}" 2>&1); then
            fail "Failed to disable ${SERVICE}. Reason: ${err}"
        fi
        ;;
    status)
        success "$(get_status)"
        ;;
    *)
        fail "Unknown argument. Available arguments: {restart|enable|disable|status}"
        ;;
esac

success
