#!/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 "${DECPASSWDLIB_VERSION:-}" ] && return 0;
DECPASSWDLIB_VERSION="0.1";
VZ_VERSION="$(cat /etc/*release /etc/issue | grep -i "virtuozzo\|parallels" | awk '{ for (i=1; i<NF; i++ ) {if ($i ~ "release" ) print $(i+1) }}' | awk -F'.' '{print $1}' | head -n 1)";

include virtuozzo;

declare -a JEM_PARAMS
function getPassword(){
        if [ -z "$1" ] ; then
                log "empty password string.";
                return 99;
        fi
        local passwString="$1";
        local rsaKey="/root/.ssh/id_rsa" ;
        local decType=${passwString%%\:*};
        local openssl_version="$(openssl version | sed -r 's/^OpenSSL[[:blank:]]+([0-9]+)[.][^[:space:]]+[[:blank:]]+.*/\1/')"
        if  (( $openssl_version >= 3 )); then
            local passwordEncrypted=$(awk -F: '{print $3}' <<<"${passwString}" 2>/dev/null)
            local openssl_parameters='-aes-256-cbc -pbkdf2 -md sha512 -iter 10000 -salt -S 429488b2f3870b4a -iv dcb9fe5ecb4011cd20114119930aadc3'
        else
            local passwordEncrypted=$(awk -F: '{print $2}' <<<"${passwString}" 2>/dev/null)
            local openssl_parameters='-aes-128-cbc -nosalt -A -nosalt'
        fi
        local keyString='';
        case ${decType,,} in
                'rsa' )
                        [ -f "$rsaKey" ] && keyString=$( cat $rsaKey )  || {  writeJSONResponseErr "result=>4087" "message=>Could not decrypt password!!"; die -q; }
                        ;;
                'static' )
                        keyString='TFVhBKDOSBspeSXesw8fElCcOzbJzYed';
                        ;;
                'envid' )
                        if [ -z "$__CTID" ] ; then
                                log "unknown __CTID. Please set it via vzexecSetCTID first";
                                return 99;
                        fi
                        if [[ "$VZ_VERSION" == "7" ]]; then
                            keyString=$(cat $(vzlist $__CTID -Ho private)/.vza/eid.conf 2>/dev/null)
                        else
                            keyString="$__CTID"
                        fi

                        ;;
                * )
                        echo "$passwString";
                        exit 0;
                        ;;
        esac
        echo $passwordEncrypted | openssl enc -d -a -pass "pass:$keyString" $openssl_parameters  2>> $ACTIONS_LOG || {  writeJSONResponseErr "result=>4087" "message=>Could not decrypt password!!"; die -q; }
}



function decryptPassword(){
    local index=0 result=0;
    JEM_PARAMS=( $@ )

    for arg in ${JEM_PARAMS[@]}
    do
	let "index+=1"
	case $arg in
	    -p|--password)
	    JEM_PARAMS[$index]=$( getPassword ${JEM_PARAMS[$index]} );
	    result=$?
	    ;;
	esac
    done
    return $result
}
