#!/bin/bash
#
# Copyright 2022 N5 Technologies, Inc.
#
# This product includes software developed at N5 Technologies, Inc
# (http://www.n5corp.com/) and software licenced to N5 Technologies,
# Inc under one or more contributor license agreements.
#
# N5 Technologies, Inc licenses this file to you under the Polyform
# Internal Use License Version 1.1.0 (the "License"); you may not use
# this file except in compliance with the License.  You may obtain a
# copy of the License at:
#
#     https://polyformproject.org/licenses/internal-use/1.0.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.
#

pushd `dirname $0`/.. > /dev/null 
. ./setenv.sh
popd > /dev/null 

# Check if -n or -name was explicitly provided in args
XVM=""
HAS_NAME_FLAG=false
for arg in "$@"; do
    if [[ $HAS_NAME_FLAG == "next" ]]; then
        XVM=$arg
        HAS_NAME_FLAG=true
        break
    fi
    if [[ $arg == "-n" || $arg == "-name" ]]; then
        HAS_NAME_FLAG="next"
    fi
done

if [[ $HAS_NAME_FLAG == true ]]; then
    # -n/-name explicitly provided, don't consume first arg
    :
elif [[ $1 = "" || $1 == -* || $1 == wrapper.* ]]; then
    XVM=default
else
    XVM=$1
    shift
fi

# Separate wrapper.* arguments from Main.java arguments
WRAPPER_PARAMS=""
if [[ $HAS_NAME_FLAG == true ]]; then
    # Name was explicitly provided via -n/-name, pass all args through
    APP_PARAMS="wrapper.app.parameter.1=--managed"
    PARAM_NUM=2
else
    APP_PARAMS="wrapper.app.parameter.1=-n wrapper.app.parameter.2=$XVM wrapper.app.parameter.3=--managed"
    PARAM_NUM=4
fi
for arg in "$@"; do
    if [[ $arg == wrapper.* ]]; then
        WRAPPER_PARAMS="$WRAPPER_PARAMS $arg"
    else
        APP_PARAMS="$APP_PARAMS wrapper.app.parameter.$PARAM_NUM=$arg"
        PARAM_NUM=$((PARAM_NUM + 1))
    fi
done

export NVWRAPPERLOGFILENAME=xvm.$XVM.log
`dirname $0`/xwrapper.sh -c $NVROOT/conf/wrapper.server.conf $WRAPPER_PARAMS $APP_PARAMS
