#!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#

export LANG=en_US.utf-8
# set -x

declare -A map_opts=(\
    ['-confMap']="true" \
    ['-runtimeMap']="true" \
    ['-varMap']="true" \
    ['-labelMap']="true" \
    ['-execMap']="true" \
    ['-sourceMap']="true" \
    ['-jobContentMap']="true" \
)

declare -A non_map_opts=(\
    ['--gatewayUrl']="1st" \
    ['--authStg']="1st" \
    ['--authKey']="1st" \
    ['--authVal']="1st" \
    ['--userConf']="1st" \
    ['--kill']="1st" \
    ['--status']="1st" \
    ['--help']="1st" \
    ['--mode']="1st" \
    ['-engineType']="1st" \
    ['-codeType']="1st" \
    ['-code']="1st" \
    ['-codePath']="1st" \
    ['-scriptPath']="1st" \
    ['-submitUser']="1st" \
    ['-proxyUser']="1st" \
    ['-creator']="1st" \
    ['-outPath']="1st" \
)

declare -a ARGS
declare -a PARSED_CMD
i=0
for arg in "$@"
do
    ARGS[i]=${arg}
    ((i++))
done
NUM_ARGS=$i

function preparse() {
    ((j=0))
    for((i=0;i<NUM_ARGS;i++));
    do
    if [ $((${i}+1)) -lt ${NUM_ARGS} ]; then
        opt=${ARGS[$i]}
        val=${ARGS[$i+1]}
        if [ -n "${non_map_opts[$opt]}" ]; then
            if [ "${non_map_opts[$opt]}"x == "1st"x  ]; then
                non_map_opts[$opt]=$((j+1))
                PARSED_CMD[$j]=$opt
                PARSED_CMD[$j+1]=$val
                ((j=j+2))
                ((i++))
            elif [ $opt == "--help" ];then
                PARSED_CMD[$j]=$opt
                ((j++))
            else
                idx=non_map_opts[$opt]
                PARSED_CMD[$idx]=$val
                ((i++))
            fi
        elif [ -n "${map_opts[$opt]}" ]; then
            PARSED_CMD[$j]=$opt
            PARSED_CMD[$j+1]=$val
            ((j=j+2))
            ((i++))
        else
            for((k=i;k<NUM_ARGS;k++));
            do
                PARSED_CMD[$j]=${ARGS[$k]}
                ((i++))
                ((j++))
            done
        fi
    else
        PARSED_CMD[$j]=${ARGS[$i]}
        ((j++))
    fi
    done
}


current_dir=`pwd`
work_dir=`dirname "$0"`/../
export WORK_DIR=`cd ${work_dir};pwd`
cd ${current_dir}/

if (( NUM_ARGS == 0 )); then
    PARSED_CMD[$j]='--help'
else
    preparse
fi

exec ${WORK_DIR}/bin/linkis-cli "${PARSED_CMD[@]}"



