#!/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 output exceptor
include vzexec virtuozzo

DESCRIPTION="JEM package installation module"
VERSION="1"
DEFAULT_ACTION="Usage"

PACKAGES=""
VEID=0

function describePackage() {
    echo "Generate and run the installation command for specified packages into the specified container"
}

function doUsage() {
    showUsageMessage
}

function onModLoadCallback() {

    local temp=`getopt -o c:,n: -l ctid:,name: -- params "$@" 2>/dev/null`
    [[ $? != 0 ]] && die -q "Terminating..."
    eval set -- "$temp"

    while true ; do
        case "$1" in
            -c | --ctid )
                shift
                VEID=$1
                vzexecSetCTID $VEID
                shift
                ;;
            -n | --name )
                shift
                PACKAGES=$1
                shift
                ;;
            --)
                shift
                break
                ;;
        esac;
    done;

    if [ ! -z "$VEID" ] ; then
        populateVEVarsVZ $VEID
        res=$?
        if [[ "$res" -eq 3 ]] ; then
            writeJSONResponseErr "result=>4003" "message=>ctid $VEID not found"
            die -q
        fi

        if [ -z "$VZ_VEID_OS" ] ; then
            writeJSONResponseErr "result=>4097" "message=>Cannot detect OS version"
            die -q
        fi
    fi
}

function describeInstallParameters() {
    echo "-n|--name <packages> -c|--ctid <container id>"
}

function describeInstallOptions() {
    echo "-n|--name: packages to be installed"
    echo "-c|--ctid: target container id"
}

function doInstall() {
    if [ -z "$PACKAGES" ]; then
        writeJSONResponseErr "result=>4058" "message=>Packages are not specified"
        return 1
    fi

    if VEExecRun "sed -rne '/CERTIFIED_VERSION=/{s/CERTIFIED_VERSION=([0-9]{1,})/\1/g;p}' /etc/jelastic/metainf.conf" ; then
        _isCertified=$(vzexecGetLastStdOut)
        echo "`date +%D.%k:%M:%S.%N`:   $action:$subaction CTID:$VEID - certified template version $_isCertified" >> $JEM_CALLS_LOG
    fi

    installCmd=$(installPackageCmd $VZ_VEID_OS install $_isCertified $PACKAGES)
    checkCmd=$(checkPackageCmd $VZ_VEID_OS $PACKAGES)

    echo "`date +%D.%k:%M:%S.%N`:   $action:$subaction CTID:$VEID - going to install $PACKAGES" >> $JEM_CALLS_LOG

    # try to run PM to install specified packages
    if ! vzexecRun "$installCmd" ; then
        #merge response to a single line and put escape a line breaks. this needed to output valid json
        echo "$(VEexecGetLastStdOut)\n$(VEexecGetLastStdErr)" | sed -r -e ':a;N;$!ba;s/\n/\\\n/g' >> $ACTIONS_LOG
        writeJSONResponseErr "result=>4140" "message=>package manager fails to install $PACKAGES"
        return 1
    fi

    # check if there are packages really installed
    VEExecRun "eval $checkCmd"
    stdout=$(VEexecGetLastStdOut)
    if [[ -n "$stdout" ]] ; then
        writeJSONResponseErr "result=>4140" "message=>failed to install following packages: $stdout"
        return 1
    fi

    writeJSONResponseOut "result=>0" "message=>packages successfully installed"
}

function describeRemoveParameters() {
    echo "-n|--name <packages> -c|--ctid <container id>"
}

function describeRemoveOptions() {
    echo "-n|--name: packages to be installed"
    echo "-c|--ctid: target container id"
}

function doRemove() {
    if [ -z "$PACKAGES" ]; then
        writeJSONResponseErr "result=>4058" "message=>Packages are not specified"
        return 1
    fi

    if VEExecRun "sed -rne '/CERTIFIED_VERSION=/{s/CERTIFIED_VERSION=([0-9]{1,})/\1/g;p}' /etc/jelastic/metainf.conf" ; then
        _isCertified=$(vzexecGetLastStdOut)
        echo "`date +%D.%k:%M:%S.%N`:   $action:$subaction CTID:$VEID - certified template version $_isCertified" >> $JEM_CALLS_LOG
    fi

    removeCmd=$(installPackageCmd $VZ_VEID_OS remove $_isCertified $PACKAGES)

    echo "`date +%D.%k:%M:%S.%N`:   $action:$subaction CTID:$VEID - going remove $PACKAGES" >> $JEM_CALLS_LOG

    # try to run PM to remove specified packages
    if ! vzexecRun "$removeCmd" ; then
        #merge response to a single line and put escape a line breaks. this needed to output valid json
        echo "$(VEexecGetLastStdOut)\n$(VEexecGetLastStdErr)" | sed -r -e ':a;N;$!ba;s/\n/\\\n/g' >> $ACTIONS_LOG
        writeJSONResponseErr "result=>4140" "message=>package manager fails to remove $PACKAGES"
        return 1
    fi

    writeJSONResponseOut "result=>0" "message=>packages successfully removed"
}

