#!/bin/bash

# Copyright: 2023 Virtuozzo International GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

inherit default os envinfo output;
inherit extendperm;

VERSION="1";
DEFAULT_ACTION="Usage";
DESCRIPTION="Manage OS services";
RAKE_DEPLOY_USER="jelastic";

function doUsage() {
    showUsageMessage;
}

function doStop(){
    [ ! -z "$1" ] && SERVICE=$1;
    stopService "$SERVICE" >> "$ACTIONS_LOG"  2>&1 ; 
    local result=$?;
    local resultCode="${result}"
    if [[ "${result}" -ne "0" ]]; then
        writeJSONResponseErr "result=>4184" "message=>Service been stopped with code $resultCode"
        return 1
    fi 
    writeJSONResponseOut "result=>0" "message=>Service been stopped with code $resultCode"
    return 0
}

function doRestart(){
    [ -f "/opt/repo/jelastic/jelastic.conf" ] && { source "/opt/repo/jelastic/jelastic.conf"; }
    
    [ "x${COMPUTE_TYPE}" == "xapache-ruby" -o "x${COMPUTE_TYPE}" == "xnginx-ruby" ] || [ "x${COMPUTE_TYPE}" == "xcartridge" -a "x${Engine_Type}" == "xruby" ] && {
        [ "x${COMPUTE_TYPE}" == "xcartridge" ] && { WEBROOT=${Webroot_Path}; }
        bundle="$(/usr/lib/rvm/bin/rvm gemdir)/bin/bundle"
        inherit ruby-common;
        bundleInstall;
        if [ -f "${WEBROOT}/ROOT/rake_deploy" ]
        then
            touch ${RAKE_DEPLOY_LOG}
            if [[ "$UID" == '0' ]]; then
                chown ${DATA_OWNER} ${RAKE_DEPLOY_LOG}
            fi  
            bundle_type=$(cat /var/lib/jelastic/env) ; 
            rake_commands=$(cat ${WEBROOT}/ROOT/rake_deploy) ;
            mv -f "${WEBROOT}/ROOT/rake_deploy" "${WEBROOT}/ROOT/rake_deploy.old" 1>>"$RAKE_DEPLOY_LOG" 2>&1;
            [ -e /etc/environment ] && . /etc/environment
            RAKE_HOME_DIR=$(echo ~jelastic)
            for command in ${rake_commands}
            do
                if [[ "$UID" == '0' ]]; then
                    runuser -l "$RAKE_DEPLOY_USER" -c "source /usr/lib/rvm/environments/base && cd "${WEBROOT}/ROOT/" && HOME=${RAKE_HOME_DIR} RAILS_ENV=${bundle_type} ${bundle} exec rake "$command" >> "$RAKE_DEPLOY_LOG" 2>&1;"
                else
                    source /usr/lib/rvm/environments/base && cd "${WEBROOT}/ROOT/" && RAILS_ENV=${bundle_type} ${bundle} exec rake "$command" >> "$RAKE_DEPLOY_LOG" 2>&1;
                fi
            done
        fi
        shopt -s dotglob;
        chown -hR "$DATA_OWNER" "${WEBROOT}/ROOT/" 2>>"$JEM_CALLS_LOG" ;
        shopt -u dotglob;
    }

    local result=0 message="Ok";
    if [ $# -gt 0 ]
    then
        serviceToRestart=$1;
    else
        serviceToRestart=${SERVICE};
    fi
    stopService "$serviceToRestart ">> "$ACTIONS_LOG" 2>&1;
    result=$?;
    if [[ "${result}" -eq "0" ]]
    then
        startService "$serviceToRestart" >> "$ACTIONS_LOG" 2>&1;
        result=$?;
        if [[ "${result}" -eq "0" ]]
        then
            [ -n "$FIREWALL_ENABLED" -a "${FIREWALL_ENABLED+xxx}" = "xxx" ] && [ "${FIREWALL_ENABLED}" -eq "1" ] && [ "$USER" == "root" ] && {
                local msg=$( doAction "firewall" "Start" )  || message="Failed to apply firewall rules"; 
            }
        else
            message="Failed to start $1";
    fi
    else
        message="Failed to stop $1";
    fi
    if [[ "${result}" -ne "0" ]]; then
        local resultMessage="result ${result} "
        writeJSONResponseErr "result=>4182" "message=>${resultMessage}${message}"
        return 1
    fi
    writeJSONResponseOut "result=>0" "message=>${resultMessage}${message}"
    return 0
}

function doStart(){
    [ ! -z "$1" ] && SERVICE=$1;
    startService "$SERVICE" >> "$ACTIONS_LOG"  2>&1 ; 
    local result=$?;
    local resultCode="${result}"
    if [[ "${result}" -ne "0" ]]; then
        writeJSONResponseErr "result=>4183" "message=>Service been started with code ${resultCode}"
        return 1
    fi 
    writeJSONResponseOut "result=>${result}" "message=>Service been started with code ${resultCode}"
}

function doReload(){
    [ ! -z "$1" ] && SERVICE=$1;
    reloadService "$SERVICE" >> "$ACTIONS_LOG"  2>&1 ; 
    local result=$?;
    local resultCode="${result}"
    if [[ "${result}" -ne "0" ]]; then
        writeJSONResponseErr "result=>4185" "message=>Service been reloaded with code ${resultCode}"
        return 1
    fi 
    writeJSONResponseOut "result=>${result}" "message=>Service been reloaded with code ${resultCode}"
}

function doEnable(){
    [ ! -z "$1" ] && SERVICE=$1;
    include sendmailextip ; isFunction "SendmailExtIp" && SendmailExtIp ;
    enableService "$SERVICE" 2345 0 >> "$ACTIONS_LOG"  2>&1 ;
    res=$?
    if [[ "$res" -ne "0" ]] ; then
        writeJSONResponseErr "result=>$res" "message=>Service been started with code $res"
        return 1
    fi
    writeJSONResponseOut "result=>$res" "message=>Service been started with code $res"
}

function postRestartCallback(){
    ExtendPerm ;
}

function postStopCallback(){
    ExtendPerm ;
}

function postStartCallback(){
    ExtendPerm ;
}

function describeStop(){
    echo "Stop service";
}

function describeStart(){
    echo "Start service";
}

function describeStopParameters() {
    echo "[service name]";
}

function describeStopOptions() {
    echo "<service name>: service to act with";
}

function describeStartParameters() {
    echo "[service name]";
}

function describeStartOptions() {
    echo "<service name>: service to act with";
}

function describeRestart(){
    echo "Restart service";
}

function describeRestartParameters() {
    echo "[service name]";
}

function describeRestartOptions() {
    echo "<service name>: service to act with";
}
