#!/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 config;
include os output virtuozzo vzexec;

DESCRIPTION="Description goes here";
VERSION="1"
DEFAULT_ACTION="Usage";

function doUsage() {
        showUsageMessage;
}

function onModLoadCallback() {
    log "Preload callback";
    local shortopts="c:,b:,n:"
    local longopts="ctid:,envid:,cmd:,cmdbase64:"

    local temp=$(getopt -o $shortopts -l $longopts -- params "$@" 2>/dev/null);
    [[ $? != 0 ]] && die -q "Terminating...";
    eval set -- "$temp";

    while true ; do
        case "$1" in
            -n   | --cmd )
                shift;
                CMD=$1;
                shift;
                ;;
            -c   | --ctid  )
                shift;
                CTID=$1;
                vzexecSetCTID $CTID
                shift;
                ;;
            --envid  )
                shift;
                ENVID=$1;
                vzexecSetENVID $ENVID
                shift;
                ;;
            -b   | --cmdbase64 )
                shift;
                CMDBASE64=$1;
                shift;
                ;;
            --)
                shift;
                break;
                ;;
        esac;
    done;
    if [[ ! -z "$CTID" ]]; then
        vzIsContainerExists $CTID || { writeJSONResponseErr "result=>4003" "message=>ctid $CTID not found"; die -q; };
    fi
    if [[ ! -z "$ENVID" ]]; then
        isVMexist $ENVID || { writeJSONResponseErr "result=>4003" "message=>envid $ENVID not found"; die -q; };
    fi
    return 0;
}

function doExec() {
    if [ -z "$CTID" ] ; then
        writeJSONResponseErr "result=>4007" "message=>CTID required"
        log "ctid required"
        return 1;
    fi

    if [ ! -z "$CMDBASE64" ] ; then
        CMD="$(echo $CMDBASE64 | base64 -d)"
    fi

    if [ -z "$CMD" ] ; then
        writeJSONResponseErr "result=>4008" "message=>cmd or CMDBASE64 required"
        log "command required"
        return 1;
    fi

    if vzexecRun "$CMD" ; then
        writeJSONResponseOut "result=>0" "message=>$(vzexecGetLastStdOut)"
    else
        writeJSONResponseErr "result=>4019" "message=>$(vzexecGetLastStdErr)"
    fi
    return 0;
}

function describeExec() {
    echo "Execute command"
}

function describeExecParameters() {
    echo "-c|--ctid <ct id> -n|--cmd <cmd> | -b|--cmdbase64 <cmd base64>"
}

function describeExecOptions() {
    echo "-c|--ctid: container id"
    echo "-n|--cmd: command to execute"
    echo "-b|--cmdbase64: command to execute base64 encoded"
}

function doExec2() {
    if [ -z "$CTID" ] ; then
        writeJSONResponseErr "result=>99" "message=>CTID required"
        log "ctid required"
        return 1
    fi

    if isContainerRunning $CTID ; then
        doExec3
    else
        writeJSONResponseErr "result=>4110" "message=>Cannot execute command. Container is not running"
    fi
}

function describeExec3() {
    echo "Execute command"
}

function describeExec3Parameters() {
    echo "-b|--cmdbase64 <cmd base64>"
}

function describeExec3Options() {
    echo "-b|--cmdbase64: command to execute base64 encoded"
}

function doExec3() {
    if [ ! -z "$CMDBASE64" ] ; then
        CMD="$(echo $CMDBASE64 | base64 -d)"
    fi

    if [ -z "$CMD" ] ; then
        writeJSONResponseErr "result=>4008" "message=>cmd or CMDBASE64 required"
        log "command required"
        return 1;
    fi

    msg=""
    
    if vzexecRun "$CMD" ; then
        msg="Success"
        res=0
    else
        msg="The operation could not be performed"
        res=4109
    fi
    stout="$(vzexecGetLastStdOut)"
    sterr="$(vzexecGetLastStdErr)"
    stdout=$($SED -re 's/\\/\\\\/g;s/"/\\"/g' <<< "$stout")
    stderr=$($SED -re 's/\\/\\\\/g;s/"/\\"/g' <<< "$sterr")
    printf "{\"result\":\"%s\",\"exitcode\":\"%s\",\"message\":\"%s\",\"stdout\":\"%s\",\"stderr\":\"%s\"}\n" "$res" "$(vzexecGetLastErrCode)" "$msg" "$stdout" "$stderr"
    return 0
}

function doExecVM() {
    if [ -z "$ENVID" ] ; then
        writeJSONResponseErr "result=>99" "message=>ENVID required"
        log "envid required"
        return 1
    fi

    if [ ! -z "$CMDBASE64" ] ; then
        CMD="$(echo $CMDBASE64 | base64 -d)"
    fi

    if [ -z "$CMD" ] ; then
        writeJSONResponseErr "result=>4008" "message=>cmd or CMDBASE64 required"
        log "command required"
        return 1;
    fi

     msg=""

    if prlExecRun "$CMD" ; then
        msg="Success"
        res=0
    else
        msg="The operation could not be performed"
        res=4109
    fi
    stout="$(vzexecGetLastStdOut)"
    sterr="$(vzexecGetLastStdErr)"
    stdout=$($SED -re 's/\\/\\\\/g;s/"/\\"/g' <<< "$stout")
    stderr=$($SED -re 's/\\/\\\\/g;s/"/\\"/g' <<< "$sterr")
    printf "{\"result\":\"%s\",\"exitcode\":\"%s\",\"message\":\"%s\",\"stdout\":\"%s\",\"stderr\":\"%s\"}\n" "$res" "$(vzexecGetLastErrCode)" "$msg" "$stdout" "$stderr"
    return 0

}