#!/bin/bash

# ------------------------------------------------------------
# Company:  Software- und Organisations-Service GmbH
# Date:     2023-11-12
# Purpose:  update job resource variable
# Platform: Linux, MacOS: bash
# ------------------------------------------------------------
#

# Example: ./js7_set_job_resource.sh --url=http://joc-2-0-primary:7446 --controller-id=controller --user=root --password=root --job-resource=/ProductDemo/Variables/pdBusinessDate --key=businessDate --env-var=BUSINESS_DATE --value=$(date +'%Y-%m-%d')
#   sets the businessDate argument to the specified value and the environment variable BUSINESS_DATE to the argument value

# Example: ./js7_set_job_resource.sh --url=https://joc-2-0-primary:7443 --cacert=$HOME/certs/root-ca.crt --controller-id=controller --user=root -p --job-resource=/ProductDemo/Variables/pdBusinessDate --key=businessDate --value=$(TZ=Europe/London date +'%Y-%m-%d')
#   sets the businessDate argument to the specfied value, asks for the password

# Example: ./js7_set_job_resource.sh --url=https://joc-2-0-primary:7443 --cacert=$HOME/certs/root-ca.crt --client-key=$HOME/certs/centostest-primary.key --client-cert=$HOME/certs/centostest-primary.crt --controller-id=controller --user=root --job-resource=/ProductDemo/Variables/pdBusinessDate --key=businessDate --value=$(TZ=Europe/London date +'%Y-%m-%d')
#   sets the businessDate argument to the specfied value, makes use of client authentication certificate

# Example: ./js7_set_job_resource.sh --url=https://joc-2-0-primary:7443 --cacert=$HOME/certs/root-ca.crt --client-key=  --controller-id=controller --user=root -p --job-resource=/ProductDemo/Variables/pdBusinessDate --key=businessDate --value=$(TZ=Europe/London date +'%Y-%m-%d')
#   sets the businessDate argument to the specfied value, makes use of client keystore for authentication

# Example: ./js7_set_job_resource.sh --url=http://joc-2-0-primary:7446 --controller-id=controller --user=root --password=root --job-resource=/ProductDemo/Variables/pdConfigurationData --key=configurationData --env-var=CONFIGURATION_DATA --file=./config.ini
#   sets the configurationData argument to the file specified and the environment variable CONFIGURATION_DATA to the argument value resulting in the path to the configuratin file at run-time

# Example: ./js7_set_job_resource.sh --url=http://joc-2-0-primary:7446 --controller-id=controller --user=root --password=root --job-resource=/ProductDemo/Variables/pdBusinessSecret --encrypt-cert=./agent.crt --prefix --key=businessSecret --env-var=BUSINESS_SECRET --value="secret"
#   sets the businessSecret argument to a value encrypted with the Agent's public key.

# Example: ./js7_set_job_resource.sh --url=http://joc-2-0-primary:7446 --controller-id=controller --user=root --password=root --job-resource=/ProductDemo/Variables/pdConfigurationDataSecret --key=configurationDataSecret --env-var=CONFIGURATION_DATA_SECRET --file=./config.ini --encrypt-cert=./agent.crt
#   sets the configurationData argument to the encrypted file specified and the environment variable CONFIGURATION_DATA_SECRET to the argument value resulting in the path to the configuratin file at run-time

set -e

# ------------------------------
# Initialize variables
# ------------------------------

joc_url=
joc_user=
joc_password=
joc_cacert=
joc_client_cert=
joc_client_key=
joc_client_keystore=
controller_id=
job_resource=
key=
value=
file=
env_var=
encrypt_cert=
curdir="$(dirname "$0")"
java_lib="$(cd "${curdir}/../lib" >/dev/null && pwd)"
timeout=15
make_dirs=
show_logs=
log_dir=
verbose=
prefix=

ok=
start_time=$(date +"%Y-%m-%dT%H-%M-%S")
response_json=
access_token=
temp_key_file=
temp_cert_file=


AskPassword() {
    joc_password="$(
        exec < /dev/tty || exit
        tty_config=$(stty -g) || exit
        trap 'stty "$tty_config"' EXIT INT TERM
        stty -echo || exit
        printf 'Password: ' > /dev/tty
        IFS= read -r password; rc=$? 2> /dev/tty
        echo > /dev/tty
        printf '%s\n' "$password"
        exit "$rc"
    )"
}

Log()
{
    if [ -n "${log_file}" ] && [ -f "${log_file}" ]
    then
        echo "$@" >> "${log_file}"
    fi

    if [ -z "${show_logs}" ]
    then
        echo "$@"
    fi
}

LogVerbose()
{
    if [ -n "${verbose}" ]
    then
        if [ -n "${log_file}" ] && [ -f "${log_file}" ]
        then
            echo "$@" >> "${log_file}"
        fi
    
        if [ -z "${show_logs}" ]
        then
            echo "$@"
        fi
    fi
}

LogWarning()
{
    if [ -n "${log_file}" ] && [ -f "${log_file}" ]
    then
        echo "[WARN]" "$@" >> "${log_file}"
    fi
    
    >&2 echo "[WARN]" "$@"
}

LogError()
{
    if [ -n "${log_file}" ] && [ -f "${log_file}" ]
    then
        echo "[ERROR]" "$@" >> "${log_file}"
    fi
    
    >&2 echo "[ERROR]" "$@"
}

Login()
{ 
    LogVerbose ".. Login"
    curl_options=(-k -L -s -S -X POST -m "${timeout}")

    if [ -n "${joc_user}" ]
    then
        if [ -n "${joc_password}" ]
        then
            curl_options+=(--user "${joc_user}":"${joc_password}")
        else
            curl_options+=(--user "${joc_user}")
        fi
    fi

    if [ "${joc_cacert}" != "" ]
    then
        curl_options+=(--cacert "${joc_cacert}")
    fi

    if [ "${joc_client_cert}" != "" ]
    then
        curl_options+=(--cert "${joc_client_cert}")
    fi

    if [ "${joc_client_key}" != "" ]
    then
        curl_options+=(--key "${joc_client_key}")
    fi

    LogVerbose ".... request:"
    LogVerbose "curl ${curl_options[*]} -H "Accept: application/json" -H "Content-Type: application/json" ${joc_url}/joc/api/authentication/login"

    response_json=$(curl "${curl_options[@]}" -H "Accept: application/json" -H "Content-Type: application/json" "${joc_url}"/joc/api/authentication/login)
    LogVerbose ".... response:"
    LogVerbose "${response_json}"

    if echo "${response_json}" | jq -e . >/dev/null 2>&1
    then
        access_token=$(echo "${response_json}" | jq -r ".accessToken // empty" | sed 's/^"//' | sed 's/"$//')
        LogVerbose ".... access token: ${access_token}"
        if [ -z "${access_token}" ]
        then
            LogError "Login failed: ${response_json}"
            exit 4
        fi
    else
        LogError "Login failed: ${response_json}"
        exit 4
    fi
}

Logout()
{
    LogVerbose ".. Logout"
    curl_options=(-k -L -s -S -X POST -m "${timeout}")

    if [ "${joc_cacert}" != "" ]
    then
        curl_options+=(--cacert "${joc_cacert}")
    fi

    if [ "${joc_client_cert}" != "" ]
    then
        curl_options+=(--cert "${joc_client_cert}")
    fi

    if [ "${joc_client_key}" != "" ]
    then
        curl_options+=(--key "${joc_client_key}")
    fi

    LogVerbose ".... request:"
    LogVerbose "curl ${curl_options[*]} -H \"X-Access-Token: ${access_token}\" -H \"Accept: application/json\" -H \"Content-Type: application/json\" ${joc_url}/joc/api/authentication/logout"

    response_json=$(curl "${curl_options[@]}" -H "X-Access-Token: ${access_token}" -H "Accept: application/json" -H "Content-Type: application/json" "${joc_url}"/joc/api/authentication/logout)
    LogVerbose ".... response:"
    LogVerbose "${response_json}"

    if echo "${response_json}" | jq -e . >/dev/null 2>&1
    then
        item=$(echo "${response_json}" | jq -r "select(.isAuthenticated == false) // empty" | sed 's/^"//' | sed 's/"$//')
        if [ -z "${item}" ]
        then
            LogError "Logout failed: ${response_json}"
            exit 4
        fi
        access_token=
    else
        LogError "Logout failed: ${response_json}"
        exit 4
    fi
}

Get_Inventory_Item()
{
    request_path=$1
    request_object_type=$2

    LogVerbose ".. Get_Inventory_Item: path: ${request_path}, object type: ${request_object_type}"
    curl_options=(-k -L -s -S -X POST -m "${timeout}")

    if [ "${joc_cacert}" != "" ]
    then
        curl_options+=(--cacert "${joc_cacert}")
    fi

    if [ "${joc_client_cert}" != "" ]
    then
        curl_options+=(--cert "${joc_client_cert}")
    fi

    if [ "${joc_client_key}" != "" ]
    then
        curl_options+=(--key "${joc_client_key}")
    fi

    request_body="{ \"path\": \"${request_path}\", \"objectType\": \"${request_object_type}\" }"
    LogVerbose ".... request:"
    LogVerbose "curl ${curl_options[*]} -H \"X-Access-Token: ${access_token}\" -H \"Accept: application/json\" -H \"Content-Type: application/json\" -d \"${request_body}\" ${joc_url}/joc/api/inventory/configuration"

    response_json=$(curl "${curl_options[@]}" -H "X-Access-Token: ${access_token}" -H "Accept: application/json" -H "Content-Type: application/json" -d "${request_body}" "${joc_url}"/joc/api/inventory/read/configuration)
    LogVerbose ".... response:"
    LogVerbose "${response_json}"

    if echo "${response_json}" | jq -e . >/dev/null 2>&1
    then
        ok=$(echo "${response_json}" | jq -r ".path // empty" | sed 's/^"//' | sed 's/"$//')
        if [ -z "${ok}" ]
        then
            response_json="{ \"arguments\": { \"${key}\": \"\\"\\"\" } }"
        fi
    else
        LogError "Get_Inventory_Item failed: ${response_json}"
        exit 4
    fi
}

Set_Inventory_Item()
{
    request_path=$1
    request_object_type=$2
    request_configuration=$3

    LogVerbose ".. Set_Inventory_Item: path: ${request_path}, object type: ${request_object_type}, configuration: ${request_configuration}"
    curl_options=(-k -L -s -S -X POST -m "${timeout}")

    if [ "${joc_cacert}" != "" ]
    then
        curl_options+=(--cacert "${joc_cacert}")
    fi

    if [ "${joc_client_cert}" != "" ]
    then
        curl_options+=(--cert "${joc_client_cert}")
    fi

    if [ "${joc_client_key}" != "" ]
    then
        curl_options+=(--key "${joc_client_key}")
    fi

    request_body="{ \"path\": \"${request_path}\", \"objectType\": \"${request_object_type}\", \"valid\": true, \"configuration\": ${request_configuration} }"
    LogVerbose ".... request:"
    LogVerbose "curl ${curl_options[*]} -H \"X-Access-Token: ${access_token}\" -H \"Accept: application/json\" -H \"Content-Type: application/json\" -d \"${request_body}\" ${joc_url}/joc/api/inventory/store"

    response_json=$(curl "${curl_options[@]}" -H "X-Access-Token: ${access_token}" -H "Accept: application/json" -H "Content-Type: application/json" -d "${request_body}" "${joc_url}"/joc/api/inventory/store)
    LogVerbose ".... response:"
    LogVerbose "${response_json}"

    if echo "${response_json}" | jq -e . >/dev/null 2>&1
    then
        ok=$(echo "${response_json}" | jq -r ".path // empty" | sed 's/^"//' | sed 's/"$//')
        if [ -z "${ok}" ]
        then
            LogError "Set_Inventory_Item failed: ${response_json}"
            exit 4
        fi
    else
        LogError "Set_Inventory_Item failed: ${response_json}"
        exit 4
    fi
}

Publish_Deployable_Item()
{
    request_path=$1
    request_object_type=$2
    request_controller_id=$3

    LogVerbose ".. Publish_Deployable_Item: path: ${request_path}, object type: ${request_object_type}"
    curl_options=(-k -L -s -S -X POST -m "${timeout}")

    if [ "${joc_cacert}" != "" ]
    then
        curl_options+=(--cacert "${joc_cacert}")
    fi

    if [ "${joc_client_cert}" != "" ]
    then
        curl_options+=(--cert "${joc_client_cert}")
    fi

    if [ "${joc_client_key}" != "" ]
    then
        curl_options+=(--key "${joc_client_key}")
    fi

    request_body="{ \"controllerIds\": [\"${request_controller_id}\"], \"store\": { \"draftConfigurations\": [{\"configuration\": { \"path\": \"${request_path}\", \"objectType\": \"${request_object_type}\" }}] }}"
    LogVerbose ".... request:"
    LogVerbose "curl ${curl_options[*]} -H \"X-Access-Token: ${access_token}\" -H \"Accept: application/json\" -H \"Content-Type: application/json\" -d \"${request_body}\" ${joc_url}/joc/api/inventory/deployment/deploy"

    response_json=$(curl "${curl_options[@]}" -H "X-Access-Token: ${access_token}" -H "Accept: application/json" -H "Content-Type: application/json" -d "${request_body}" "${joc_url}"/joc/api/inventory/deployment/deploy)
    LogVerbose ".... response:"
    LogVerbose "${response_json}"

    if echo "${response_json}" | jq -e . >/dev/null 2>&1
    then
        ok=$(echo "${response_json}" | jq -r "select(.ok == true) // empty" | sed 's/^"//' | sed 's/"$//')
        if [ -z "${ok}" ]
        then
            LogError "Publish_Deployable_Item failed: ${response_json}"
            exit 4
        fi
    else
        LogError "Publish_Deployable_Item failed: ${response_json}"
        exit 4
    fi
}

Usage()
{
    >&2 echo ""
    >&2 echo "Usage: $(basename "$0") [Options] [Switches]"
    >&2 echo ""
    >&2 echo "  Options:"
    >&2 echo "    --url=<url>                   | required: JOC Cockpit URL"
    >&2 echo "    --controller-id=<identifier>  | required: Controller ID"
    >&2 echo "    --user=<account>              | required: JOC Cockpit user account"
    >&2 echo "    --password=<password>         | optional: JOC Cockpit password or Client Keystore password"
    >&2 echo "    --job-resource=<path>         | required: path to job resource"
    >&2 echo "    --key=<identifier>            | required: name of argument in job resource"
    >&2 echo "    --value=<string>              | alternate: value of argument in job resource"
    >&2 echo "    --file=<path>                 | alternate: value of argument in job resource from a file"
    >&2 echo "    --env-var=<identifier>        | optional: name of environment variable in job resource"
    >&2 echo "    --java-home=<directory>       | optional: Java Home directory for use with encryption"
    >&2 echo "    --java-lib=<directory>        | optional: Java library directory for use with encryption, default: ${java_lib}"
    >&2 echo "    --java-options=<options>      | optional: Java Options for use with encryption"
    >&2 echo "    --encrypt-cert=<path>         | optional: path to certificate or public key used to encrypt value"
    >&2 echo "    --cacert=<path>               | optional: path to Root CA Certificate for HTTPS connections"
    >&2 echo "    --client-cert=<path>          | optional: path to Client Certificate file (PEM) for HTTPS mutual authentication"
    >&2 echo "    --client-key=<path>           | optional: path to Client Private Key file (PEM) for HTTPS mutual authentication"
    >&2 echo "    --client-keystore=<path>      | optional: path to Client Keystore file (PKCS12) holding Private Key/Certificate for HTTPS mutual authentication"
    >&2 echo "    --timeout=<seconds>           | optional: timeout for connections to JOC Cockpit in seconds, default: ${timeout}"
    >&2 echo "    --log-dir=<directory>         | optional: log directory for log output of this script"
    >&2 echo ""
    >&2 echo "  Switches:"
    >&2 echo "    -h | --help                   | displays usage"
    >&2 echo "    -v | --verbose                | shows verbose log output"
    >&2 echo "    -p | --password               | asks for password"
    >&2 echo "    -r | --prefix                 | specifies that encrypted values are prefixed with enc:"
    >&2 echo "    --show-logs                   | shows log output if --log-dir is used"
    >&2 echo "    --make-dirs                   | creates directories if they do not exist"
    >&2 echo ""
}

# ------------------------------
# Process command line arguments
# ------------------------------

Arguments()
{
    for option in "$@"
    do
        case "${option}" in
            # Options
            --url=*)                joc_url=$(echo "${option}" | sed 's/--url=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --controller-id=*)      controller_id=$(echo "${option}" | sed 's/--controller-id=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --user=*)               joc_user=$(echo "${option}" | sed 's/--user=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --password=*)           joc_password=$(echo "${option}" | sed 's/--password=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --cacert=*)             joc_cacert=$(echo "${option}" | sed 's/--cacert=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --client-cert=*)        joc_client_cert=$(echo "${option}" | sed 's/--client-cert=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --client-key=*)         joc_client_key=$(echo "${option}" | sed 's/--client-key=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --client-keystore=*)    joc_client_keystore=$(echo "${option}" | sed 's/--client-keystore=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --timeout=*)            timeout=$(echo "${option}" | sed 's/--timeout=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --log-dir=*)            log_dir=$(echo "${option}" | sed 's/--log-dir=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --job-resource=*)       job_resource=$(echo "${option}" | sed 's/--job-resource=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --key=*)                key=$(echo "${option}" | sed 's/--key=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --value=*)              value=$(echo "${option}" | sed 's/--value=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --file=*)               file=$(echo "${option}" | sed 's/--file=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --env-var=*)            env_var=$(echo "${option}" | sed 's/--env-var=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --java-home=*)          java_home=$(echo "${option}" | sed 's/--java-home=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --java-lib=*)           java_lib=$(echo "${option}" | sed 's/--java-lib=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --java-options=*)       java_options=$(echo "${option}" | sed 's/--java-options=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;
            --encrypt-cert=*)       encrypt_cert=$(echo "${option}" | sed 's/--encrypt-cert=//' | sed 's/^"//' | sed 's/"$//' | sed 's/^\(.*\)\/$/\1/')
                                    ;;

            # Switches
            -h|--help)              Usage
                                    exit
                                    ;;
            -v|--verbose)           verbose=1
                                    ;;
            -p|--password)          AskPassword
                                    ;;
            -r|--prefix)            prefix=enc:
                                    ;;
            --make-dirs)            make_dirs=1
                                    ;;
            --show-logs)            show_logs=1
                                    ;;
            *)                      >&2 echo "unknown option: ${option}"
                                    Usage
                                    exit 1
                                    ;;
        esac
    done

    if ! command -v jq &> /dev/null
    then
        LogError "jq utility not found"
        exit 1
    fi

    if [ -z "${joc_url}" ]
    then
        LogError "JOC Cockpit URL must be specified: --url="
        Usage
        exit 1
    fi

    if [ -z "${controller_id}" ]
    then
        LogError "Controller ID must be specified: --controller-id="
        Usage
        exit 1
    fi

    #if [ -z "${joc_user}" ]
    #then
    #    LogError "JOC Cockpit user account not specified: --user=<account>"
    #    Usage
    #    exit 1
    #fi

    if [ -z "${job_resource}" ]
    then
        LogError "Job Resource path must be specified: --job-resource="
        Usage
        exit 1
    fi

    if [ -z "${key}" ]
    then
        LogError "Job Resource variable key must be specified: --key="
        Usage
        exit 1
    fi

    if [ -z "${value}" ] && [ -z "${file}" ]
    then
        LogError "Job Resource variable value or file must be specified: --value= or --file="
        Usage
        exit 1
    fi

    if [ -n "${value}" ] && [ -n "${file}" ]
    then
        LogError "Job Resource variable value allows one source: --value= or --file="
        Usage
        exit 1
    fi

    if [ -n "${file}" ] && [ ! -f "${file}" ]
    then
        LogError "File holding value for Job Resource variable not found: --file=${file}"
        Usage
        exit 1
    fi

    if [ -n "${java_home}" ] && [ ! -d "${java_home}" ]
    then
        LogError "Java Home directory not found: --java-home=${java_home}"
        Usage
        exit 1
    fi

    if [ -n "${java_home}" ] && [ ! -f "${java_home}"/bin/java ]
    then
        LogError "Java binary ./bin/java not found in Java Home directory: --java-home=${java_home}/bin/java"
        Usage
        exit 1
    fi

    if [ -n "${java_lib}" ] && [ ! -d "${java_lib}" ]
    then
        LogError "Java library directory not found: --java-lib=${java_lib}"
        Usage
        exit 1
    fi

    if [ -n "${encrypt_cert}" ]
    then
        if [ -n "${java_home}" ]
        then
            JAVA_HOME=${java_home}
            JAVA=${java_home}/bin/java
        else
            java_bin=$(which java 2>/dev/null || echo "")
            test -n "${JAVA_HOME}" && test -x "${JAVA_HOME}/bin/java" && java_bin="${JAVA_HOME}/bin/java"
            if [ -z "${java_bin}" ]
            then
                LogError "could not identify Java environment, please set JAVA_HOME variable or use: --java-home=<directory>"
                exit 2
            fi

            JAVA=${java_bin}
        fi
    fi

    if [ -n "${encrypt_cert}" ] && [ ! -f "${encrypt_cert}" ]
    then
        LogError "Certificate file not found: --encrypt-cert=${encrypt_cert}"
        Usage
        exit 1
    fi

    if [ -n "${joc_cacert}" ] && [ ! -f "${joc_cacert}" ]
    then
        LogError "Root CA Certificate file not found: --cacert=${joc_cacert}"
        Usage
        exit 1
    fi

    if [ -n "${joc_client_cert}" ] && [ ! -f "${joc_client_cert%:*}" ]
    then
        LogError "Client Certificate file not found: --client-cert=${joc_client_cert}"
        Usage
        exit 1
    fi

    if [ -n "${joc_client_key}" ] && [ ! -f "${joc_client_key%:*}" ]
    then
        LogError "Client Private Key file not found: --client-key=${joc_client_key}"
        Usage
        exit 1
    fi

    if [ -n "${joc_client_keystore}" ] && [ ! -f "${joc_client_keystore}" ]
    then
        LogError "Client Keystore file not found: --client-keystore=${joc_client_keystore}"
        Usage
        exit 1
    fi

    if [ -n "${show_logs}" ] && [ -z "${log_dir}" ]
    then
        LogError "Log directory not specified and --show-logs switch is present: --log-dir="
        Usage
        exit 1
    fi

    if [ -z "${make_dirs}" ] && [ -n "${log_dir}" ] && [ ! -d "${log_dir}" ]
    then
        LogError "Log directory not found and --make-dirs switch not present: --log-dir=${log_dir}"
        Usage
        exit 1
    fi

    # initialize logging
    if [ -n "${log_dir}" ]
    then
        # create log directory if required
        if [ ! -d "${log_dir}" ] && [ -n "${make_dirs}" ]
        then
            mkdir -p "${log_dir}"
        fi
    
        log_file="${log_dir}"/set_job_resource."${start_time}".log
        while [ -f "${log_file}" ]
        do
            sleep 1
            start_time=$(date +"%Y-%m-%dT%H-%M-%S")
            log_file="${log_dir}"/set_job_resource."${start_time}".log
        done
        
        touch "${log_file}"
    fi

    LogVerbose "-- begin of log --------------"
    LogVerbose "$0" "$@"
    LogVerbose "-- begin of output -----------"
}

# ------------------------------
# Process Job Resource
# ------------------------------

Process()
{
    if [ -n "${joc_client_keystore}" ]
    then
        temp_key_file=./set_job_resource-client-$$.key
        joc_client_key="${temp_key_file}"
        openssl pkcs12 -in "${joc_client_keystore}" -passin pass:"${joc_password}" -passout pass:"${joc_password}" -nocerts -out "${temp_key_file}"

        temp_cert_file=./js7_sign_$$.crt
        joc_client_cert="${temp_cert_file}"
        openssl pkcs12 -in "${joc_client_keystore}" -passin pass:"${joc_password}" -passout pass:"${joc_password}" -nokeys -out "${temp_cert_file}"
    fi

    Login
    Get_Inventory_Item "${job_resource}" "JOBRESOURCE"

    if [ -n "${file}" ]
    then
        if [ -n "${encrypt_cert}" ]
        then
            temp_encrypted_file=/tmp/js7_set_job_resource-client-$$.file
            java_classpath="${java_lib}/patches/*:${java_lib}/sos/*:${java_lib}/3rd-party/*:${java_lib}/stdout"
            result=$("${JAVA}" -classpath "${java_classpath}" com.sos.commons.encryption.executable.Encrypt --cert="${encrypt_cert}" --infile="${file}" --outfile="${temp_encrypted_file}")

            if [ "${result#*" "}" = "${result}" ]
            then
                LogError "no valid encryption result"
                exit 2
            fi

            if [ -n "${prefix}" ]
            then
                result="${prefix}""${result}"
            fi

            response_json=$(echo "${response_json}" | jq ".configuration.arguments |= . + { \"${key}_key\" : \"\\\"${result}\\\"\" } | .")
            request_job_resource=$(echo "${response_json}" | jq ".configuration.arguments |= . + { \"${key}\" : \"toFile( '$(cat "${temp_encrypted_file}")', '*.${temp_encrypted_file##*.}')\" } | .configuration")
            
            if [ "${env_var}" ]
            then
                request_job_resource=$(echo "${request_job_resource}" | jq " .env |= . + { \"${env_var}_key\" : \"\$${key}_key\" } | .")
            fi
        else
            request_job_resource=$(echo "${response_json}" | jq ".configuration.arguments |= . + { \"${key}\" : \"toFile( '$(cat "${file}")', '*.${file##*.}')\" } | .configuration")
        fi
    else
        if [ -n "${encrypt_cert}" ]
        then
            java_classpath="${java_lib}/patches/*:${java_lib}/sos/*:${java_lib}/3rd-party/*:${java_lib}/stdout"
            result=$("${JAVA}" -classpath "${java_classpath}" com.sos.commons.encryption.executable.Encrypt --cert="${encrypt_cert}" --in="${value}")

            if [ "${result#*" "}" = "${result}" ]
            then
                LogError "no valid encryption result"
                exit 2
            fi
            
            if [ -n "${prefix}" ]
            then
                result="${prefix}""${result}"
            fi

            request_job_resource=$(echo "${response_json}" | jq ".configuration.arguments |= . + { \"${key}\" : \"\\\"${result}\\\"\" } | .configuration")
        else
            request_job_resource=$(echo "${response_json}" | jq ".configuration.arguments |= . + { \"${key}\" : \"\\\"${value}\\\"\" } | .configuration")
        fi
    fi

    if [ "${env_var}" ]
    then
        request_job_resource=$(echo "${request_job_resource}" | jq " .env |= . + { \"${env_var}\" : \"\$${key}\" } | .")
    fi
    
    Set_Inventory_Item "${job_resource}" "JOBRESOURCE" "${request_job_resource}"

    Publish_Deployable_Item "${job_resource}" "JOBRESOURCE" "${controller_id}"
    Logout
}

# ------------------------------
# Cleanup temporary resources
# ------------------------------

End()
{   
    if [ -n "${access_token}" ]
    then
        Logout
    fi

    if [ -n "${temp_key_file}" ] && [ -f "${temp_key_file}" ]
    then
        rm -f "${temp_key_file}"
    fi

    if [ -n "${temp_cert_file}" ] && [ -f "${temp_cert_file}" ]
    then
        rm -f "${temp_cert_file}"
    fi
    
    if [ -n "${temp_encrypted_file}" ] && [ -f "${temp_encrypted_file}" ]
    then
        rm -f "${temp_encrypted_file}"
    fi
    
    if [ "$1" = "EXIT" ]
    then
        LogVerbose "-- end of log ----------------"

        if [ -n "${show_logs}" ] && [ -f "${log_file}" ]
        then
            cat "${log_file}"
        fi        
    fi

    unset joc_url
    unset joc_cacert
    unset joc_client_cert
    unset joc_client_key
    unset joc_client_keystore
    unset joc_user
    unset joc_password
    unset controller_id
    unset job_resource
    unset key
    unset value
    unset file
    unset env_var
    unset encrypt_cert
    unset java_home
    unset java_lib
    unset java_options
    unset timeout
    unset make_dirs
    unset show_logs
    unset log_dir
    unset verbose
    unset prefix

    unset ok
    unset start_time
    unset response_json
    unset access_token
    unset request_job_resource
    unset temp_key_file
    unset temp_cert_file
    unset temp_encrypted_file

    set +e
}

# ------------------------------
# Enable trap and start
# ------------------------------

trap 'End EXIT' EXIT
trap 'End SIGTERM' TERM
trap 'End SIGINT' INT

Arguments "$@"
Process
