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

$PROGRAM 'sed';
$PROGRAM 'grep';


DESCRIPTION="Jem configuration module";
VERSION="1";
DEFAULT_ACTION="Usage";

function doUsage() {
    showUsageMessage;
}

function checkParams() {
    local params=($*)
    local result=""
    for p in ${params[*]} ; do
        eval "[[ -z \"\$$p\" ]] && { result=\"$p $result\";}"
    done
    [[ -z "$result" ]] && return 0;
    echo $result;
    return 1;
}

function onModLoadCallback() {
    log "Preload callback";

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

    while true ; do
        case "$1" in
            -c | --ctid)
                shift;
                CTID=$1
                vzexecSetCTID ${CTID}
                shift;
                ;;
            --)
                shift;
                break;
                ;;
        esac;
    done;
    for arg do UNKNOWN_ARG+=("$arg") ; done
    log "${UNKNOWN_ARG[*]}"
    return 0
}

function doSetTechEmail(){
        local techemail="${1}";
        [[ -n "${META_FILE}" ]] && [[ -e "${META_FILE}" ]] && {
        if $GREP -q "PLATFORM_TECHMAIL_RECEPIENT=$techemail" ${META_FILE} ; then
            $SED -c -i "s/\(PLATFORM_TECHMAIL_RECEPIENT *= *\).*/\1$PLATFORM_TECHMAIL_RECEPIENT/" ${META_FILE};
        else
            echo -e "\nPLATFORM_TECHMAIL_RECEPIENT=$PLATFORM_TECHMAIL_RECEPIENT" >> ${META_FILE};
            $SED -i -re '/^$/d' ${META_FILE};
        fi;
        }
}

function doExtIpChanged(){
    inherit $extipchange_module_inherit ;
    inherit sendmailextip ; SendmailExtIp ;
    ipChanged ;
    writeJSONResponseOut "result=>0" "message=>Ok"
}

function doIpChanged() {
    local vzcomment='# Auto-generated hostname. Please do not remove this comment.'
    local requiredParqams=("CTID")
    local msg=$(checkParams ${requiredParqams[@]})
    [[ ! -z "${msg}" ]] && { writeJSONResponseErr "result=>4099" "message=>Missing param $msg" ; return 99; }

    isContainerRunning $CTID || {
        writeJSONResponseOut "result=>0" "message=>Ok"
        return 0 
    }
    
    #remove line after "VZMarker"
    vzexecRun 'sed -i -re "/'$vzcomment'/{N;d}" /etc/hosts'

    #get new ip address
    vzexecRun 'ip r get 8.8.8.8 | sed -rne "/src/s/(.*)src\ (.*)/\2/p"'
    newIp=$(vzexecGetLastStdOut)

    #get hosname
    vzexecRun 'hostname -f'
    fullHostname=$(vzexecGetLastStdOut)
    vzexecRun 'hostname -s'
    shortHostname=$(vzexecGetLastStdOut)
    newHostsLine="$vzcomment\n$newIp $fullHostname $shortHostname\n"
    echo -e $newHostsLine >> "/vz/root/${CTID}/etc/hosts"

    #cleanup empty lines :)
    vzexecRun 'sed -i -e "/^$/d" /etc/hosts'

    writeJSONResponseOut "result=>0" "message=>Ok"
}

function doOption(){
    OPTION_ENABLED=0;
    while [ "$1" != "" ];
    do
        case $1 in
            -o| --option ) shift
                MANAGE_OPTION=$( tr '[:lower:]' '[:upper:]'  <<< $1 ) ;;
            -e| --enable )
                OPTION_ENABLED=1 ;;
            -d| --disable )
                OPTION_ENABLED=0 ;;
        esac
        shift
    done
    [ -z "$MANAGE_OPTION" ] && { writeJSONResponseErr "result=>4099" "message=>Missing param" ; return 99; }

    [[ -n "${META_FILE}" ]] && [[ -e "${META_FILE}" ]] && {
        if $GREP -q "${MANAGE_OPTION}_ENABLED" ${META_FILE} ; then
            $SED -i -re "s/${MANAGE_OPTION}_ENABLED=([0-9]+)/${MANAGE_OPTION}_ENABLED=${OPTION_ENABLED}/g" ${META_FILE};
        else
            echo -e "\n${MANAGE_OPTION}_ENABLED=${OPTION_ENABLED}" >> ${META_FILE};
            $SED -i -re '/^$/d' ${META_FILE};
        fi;
    } || {
        writeJSONResponseErr "result=>4080" "message=>Error: No metadata found!" ;
        return 80;
    }
    if [ "x$MANAGE_OPTION" == "xSENDMAIL" ]; then
        inherit sendmailextip ; SendmailExtIp ;
    fi
    writeJSONResponseOut "result=>0" "message=>Option ${MANAGE_OPTION} configured successfully"
    return 0;
}

function describeOption(){
    echo "Set/unset provided option"
}

function describeOptionParameters(){
    echo "--option <option> --enable|--disable"
}

function describeOptionOptions(){
    echo "-o|--option <option>: target option";
    echo "-e|--enable: enable option";
    echo "-d|--disable: disable option";
}

function describeExtIpChanged() {
    echo "Configure after add/remove external IP";
}

function describeSetTechEmail() {
    echo "Set email recipient";
}

function describeSetTechEmailParameters() {
    echo "<email>";
}

function describeSetTechEmailOptions() {
    echo "<email>: email address of technical recipient";
}
