#!/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.

[ -n "${HOOKSLIB_VERSION:-}" ] && return 0;
HOOKSLIB_VERSION="0.1";

HOOKS_DIR="/var/lib/jelastic/hooks";
[ ! -d ${HOOKS_DIR} ] && mkdir -p ${HOOKS_DIR};

if [ -f /etc/jelastic/redeploy.conf ] && [ -z $(grep ${HOOKS_DIR} /etc/jelastic/redeploy.conf) ]; then
    echo ${HOOKS_DIR} >> /etc/jelastic/redeploy.conf
fi

function getHooksLogName()
{
    [ -n "${VCS_UPDATE_LOG}" ] && HOOKS_LOG="$(dirname ${VCS_UPDATE_LOG})/hooks.log";

    case ${COMPUTE_TYPE} in
        tomcat)
                HOOKS_LOG="/opt/tomcat/logs/hooks.log";
        ;;
        jetty)
                HOOKS_LOG="/opt/jetty/logs/hooks.log";
        ;;
        glassfish|payara|wildfly)
                HOOKS_LOG="/var/log/hooks.log";
        ;;
    esac

    [ -z "${HOOKS_LOG}" ] && HOOKS_LOG="${ACTIONS_LOG}";    
}

function applyHook(){
    target="$1"
    hook="$2"
    [ "x${target}" == "xroot" ] && target="ROOT";
    adjustRubyTarget;
    hookDisplayName=$(echo $hook | sed -r 's/([a-z0-9])([A-Z])/\1-\L\2/g'|sed 's/.*/\u&/')
    if [ -f "$HOOKS_DIR/${hook}_${target}.sh" ]; then
        getHooksLogName;
        touch ${HOOKS_LOG};
        resultFile=$(mktemp); export resultFile;
        [ "x${COMPUTE_TYPE}" == "xmaven" ] && local WRITE_OUTPUT_TO="${LOG_DIR}/${PROJECT_NAME}_build.log" || local WRITE_OUTPUT_TO="${ACTIONS_LOG}";
        echo -e "[INFO] $(date) Applying ${hookDisplayName} hook for ${target} \n" | tee -a ${WRITE_OUTPUT_TO} >> ${HOOKS_LOG};
        ${SUDO_COMMAND} chmod +x "$HOOKS_DIR/${hook}_${target}.sh";
        if [ "$UID" == '0' ]; then
            chown ${DATA_OWNER} ${HOOKS_LOG} ${resultFile} ;
            runuser -l jelastic -c "timeout ${actiontimeout} $HOOKS_DIR/${hook}_${target}.sh 2>&1; echo \$?>${resultFile}" | tee -a ${WRITE_OUTPUT_TO} >> ${HOOKS_LOG};
        else
            (timeout ${actiontimeout} $HOOKS_DIR/${hook}_${target}.sh 2>&1; echo $?>${resultFile}) | tee -a ${WRITE_OUTPUT_TO} >> ${HOOKS_LOG};
        fi
        result=$(cat ${resultFile}); rm -f ${resultFile};
        if [ "${result}" == "0" ]; then
            echo -e "[INFO] $(date) ${hookDisplayName} hook applied successfully\n\n" | tee -a ${WRITE_OUTPUT_TO} >> ${HOOKS_LOG};
        elif [ "${result}" == "124" ]; then
            echo -e "[ERROR] $(date) ${hookDisplayName} hook execution timed out. Exit code ${result}\n\n" | tee -a ${WRITE_OUTPUT_TO} >> ${HOOKS_LOG}; die -q;
        else
            echo -e "[ERROR] $(date) ${hookDisplayName} hook execution failed. Exit code ${result}\n\n" | tee -a ${WRITE_OUTPUT_TO} >> ${HOOKS_LOG};
        fi
        if [ "$UID" == '0' ]; then
            if [ -e "${WEBROOT}/${target}" ]; then
                chown -R ${DATA_OWNER} ${WEBROOT}/${target};
            else
                true
            fi
        fi 
        return ${result}
    else
        return 0;
    fi
}

function renameHooks(){
    target="$1"
    old_target="$2"
    [ ! -d ${HOOKS_DIR} ] && return 0;
    adjustRubyTarget;
    [ -z "${hooks_to_rename}" ] && hooks_to_rename=$(ls ${HOOKS_DIR}|grep "${old_target}.sh")
    for i in ${hooks_to_rename}
    do
        [ "${HOOKS_DIR}/$i" != "${HOOKS_DIR}/$(echo $i|cut -d"_" -f1)_${target}.sh" ] && mv -f ${HOOKS_DIR}/$i ${HOOKS_DIR}/$(echo $i|cut -d"_" -f1)_${target}.sh;
    done
}

function removeHooks(){
    getHooksLogName;
    target="$1"
    adjustRubyTarget;
    [ -z "${hooks_to_delete}" ] && hooks_to_delete=$(ls ${HOOKS_DIR}|grep "_${target}.sh")
    if [ -n "${hooks_to_delete}" ]; then
        rm -f "$HOOKS_DIR/*_${target}.sh" && echo -e "[INFO] $(date) All hooks are removed for ${target}" >> ${HOOKS_LOG};
    else
        return 0;
    fi
}

function adjustRubyTarget(){
    [ "${COMPUTE_TYPE}" == "apache-ruby" -o "${COMPUTE_TYPE}" == "nginx-ruby" ] || [ "x${COMPUTE_TYPE}" == "xcartridge" -a "x${Engine_Type}" == "xruby" ] && { [ -f /etc/environment ] && ${SUDO_COMMAND} chmod 666 /etc/environment; target="${bundle_type}"; [ -z "${target}" ] && target=${context}; [ -d ${HOOKS_DIR} ]  && hooks_to_delete=$(ls ${HOOKS_DIR}) && hooks_to_rename=${hooks_to_delete}; }
}
