#!/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 "${JAVACOMMONDEPLOYLIB_VERSION:-}" ] && return 0;
JAVACOMMONDEPLOYLIB_VERSION="0.1";
$PROGRAM 'grep';

inherit default exceptor;

TOMCAT_CONF_DIR=$TOMCAT_HOME'conf/'
SERVERXML=$TOMCAT_CONF_DIR"server.xml"

[ ! -z "$WEBROOT" -a ! -d "$WEBROOT" ] && mkdir -p ${WEBROOT};

[ ${COMPUTE_TYPE} == "tomee" ] && COMPUTE_TYPE="tomcat" ;
[ -e "${MANAGE_CORE_PATH}/${COMPUTE_TYPE}"-deploy.lib ] && { include ${COMPUTE_TYPE}-deploy; }

[ -f /.jelenv ] && export $(grep HOT_DEPLOY /.jelenv 2>/dev/null | tr -d '"') >/dev/null

HOT_DEPLOY=${HOT_DEPLOY^^}

function verifyUnpackedContent(){
    
    if [ -e ${SERVERXML} ]; then 
        $GREP -q unpackWARs=[\'\"]false[\'\"] ${SERVERXML} && return 0;
    fi 
    
    local context=$1
    local pull_inverval_for_content=2s;
    local pull_inverval_for_directory=2s;
    local content_size_step1 content_size_step2;
    local attempt_amount=390
    local attempt_num=0;

    while [ true ]
    do

        local content_path;

        [ ${COMPUTE_TYPE} == "tomcat" ] && {
                    content_path="${WEBROOT}/${context}";
                    grep -q '\#' <<< $context && return 0;
        };

        [ ${COMPUTE_TYPE} == "jetty" ] && [ ${COMPUTE_TYPE_VERSION} == "6" ] && {
                    local jetty_context_dir=$(ls -1 ${WORKDIR}/ | $GREP ${context} | head -n 1);
                    [ ! -z $jetty_context_dir  ] &&  content_path="${WORKDIR}/${jetty_context_dir}" || content_path="NoPath";
        };

        [ -d $content_path ] && {

            content_size_step1=$(du -s $content_path);
            sleep $pull_inverval_for_content;
            content_size_step2=$(du -s $content_path);
            [[ $content_size_step1 == $content_size_step2 ]] && return 0;
        } || let $(( attempt_num ++ ));
        sleep $pull_inverval_for_directory;
        [ $attempt_num -gt $attempt_amount ] && writeJSONResponseErr "result=>4071" "message=>Cannot unpack pakage" && exit 1;
    done
}

function deploy(){

    if [[ -z "$package_url" || -z "$context" ]]
    then
        echo "Wrong arguments for deploy" 1>&2;
        exit 1;
    fi
    clearCache;
    getPackageName;
    ensureFileCanBeUncompressed "${package_path}/${package_name}";

    if [ "x$HOT_DEPLOY" != "x1" ] && [ "x$HOT_DEPLOY" != "xENABLED" ] && [ "x$HOT_DEPLOY" != "xTRUE" ]; then
        stopServiceSilent ${SERVICE} ;
    fi

    if [ -e "${WEBROOT}/$context" ]
    then
        set -f
        rm -fr ${WEBROOT}/$context;
        set +f
    fi

    applyPreDeploy;

    echo $package_name | $GREP -qP "ear$" && ext="ear" || ext="war";

    if [[ ${ext} == "ear" ]]
    then
        [ ! -d  $APPS_DIR ] && mkdir -p $APPS_DIR && chown -R  $DATA_OWNER  ${APPS_DIR} 2>>"$JEM_CALLS_LOG";
        /bin/cp "${package_path}/${package_name}" "${APPS_DIR}/${context}.${ext}" 2>>"$JEM_CALLS_LOG";
        [ -f "${APPS_DIR}/${context}.war" ] && rm -f "${APPS_DIR}/${context}.war";
        [ "$UID" == '0' ] && chown -R $DATA_OWNER "${APPS_DIR}/${context}.${ext}"
    else
        /bin/cp "${package_path}/${package_name}" "${WEBROOT}/${context}.${ext}" 2>>"$JEM_CALLS_LOG";
        [ -f "${APPS_DIR}/${context}.ear" ] && rm -f "${APPS_DIR}/${context}.ear";
        [ "$UID" == '0' ] && chown -R $DATA_OWNER "${WEBROOT}/${context}.${ext}"
    fi

    applyPostDeploy;
    clearCache;

    if [ "x$HOT_DEPLOY" != "x1" ] && [ "x$HOT_DEPLOY" != "xENABLED" ] && [ "x$HOT_DEPLOY" != "xTRUE" ]; then
        startServiceSilent ${SERVICE} ;
    fi

    verifyUnpackedContent "${context}";

}

function undeploy(){
    if [[ -z "$context" ]]
    then
        echo "Wrong arguments for undeploy" 1>&2
        exit 1
    fi

    applyPreUndeploy;

    [ -f ${WEBROOT}/${context}.war ] && rm -f ${WEBROOT}/${context}.war
    [ -f ${APPS_DIR}/${context}.ear ] && rm -f ${APPS_DIR}/${context}.ear

    applyPostUndeploy;

}

function renameContext(){

    if [[ -z "newContext" || -z "$oldContext" ]]
    then
        echo "Wrong arguments for rename" 1>&2
        exit 1
    fi
    if [ "x$HOT_DEPLOY" != "x1" ] && [ "x$HOT_DEPLOY" != "xENABLED" ] && [ "x$HOT_DEPLOY" != "xTRUE" ]; then
        stopServiceSilent ${SERVICE} ;
    fi
    applyPreRename;
    shopt -s dotglob;
    [ -e ${WEBROOT}/${oldContext}.war ] && mv ${WEBROOT}/${oldContext}.war  ${WEBROOT}/${newContext}.war && war_deploy_result=0 || war_deploy_result=1;
    [ -e ${APPS_DIR}/${oldContext}.ear ] && mv ${APPS_DIR}/${oldContext}.ear  ${APPS_DIR}/${newContext}.ear && ear_deploy_result=0 || ear_deploy_result=1;
    [ $(( $war_deploy_result & $ear_deploy_result )) -ne 0  ] && {
        shopt -u dotglob;
        if [ "x$HOT_DEPLOY" != "x1" ] && [ "x$HOT_DEPLOY" != "xENABLED" ] && [ "x$HOT_DEPLOY" != "xTRUE" ]; then
            startServiceSilent ${SERVICE};
        fi
        writeJSONResponseErr "result=>4052" "message=>Context does not exist";
        die -q;
    }

    shopt -u dotglob;
    applyPostRename;
    if [ "x$HOT_DEPLOY" != "x1" ] && [ "x$HOT_DEPLOY" != "xENABLED" ] && [ "x$HOT_DEPLOY" != "xTRUE" ]; then
        startServiceSilent ${SERVICE} ;
    fi
    verifyUnpackedContent "${newContext}";
}

function describeDeploy(){
    echo "deploy java application \n\t\t -p \t <package URL> \n\t\t -c
\t <context> \n\t\t ";
}

function describeUndeploy(){
    echo "undeploy java application \n\t\t -c \t <context>";
}

function describeRename(){
    echo "rename java context \n\t\t -n \t <new context> \n\t\t -o \t
<old context>\n\t\t";
}
