@rem ===
@rem Copyright 2022 N5 Technologies, Inc.
@rem
@rem This product includes software developed at N5 Technologies, Inc
@rem (http://www.n5corp.com/) and software licenced to N5 Technologies,
@rem Inc under one or more contributor license agreements.
@rem
@rem N5 Technologies, Inc licenses this file to you under the Polyform
@rem Internal Use License Version 1.1.0 (the "License"); you may not use
@rem this file except in compliance with the License.  You may obtain a
@rem copy of the License at:
@rem
@rem     https://polyformproject.org/licenses/internal-use/1.0.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem ===

@echo off
@setlocal EnableDelayedExpansion
@pushd %~dp0\..
@call setenv.bat
@popd
@rem Check if -n or -name was explicitly provided in args
@set XVM=
@set HAS_NAME_FLAG=false
@set SCAN_ARGS=%*
@call :SCANARGS %SCAN_ARGS%
@if "!HAS_NAME_FLAG!"=="true" goto :RESOLVEDONE
@rem No explicit -n/-name found, use positional logic
@if "%~1"=="" goto :NOPARAM
@set ARG=%~1
@if "!ARG:~0,1!"=="-" goto :NOPARAM
@if "!ARG:~0,8!"=="wrapper." goto :NOPARAM
@set XVM=%1
@shift
@goto :RESOLVEDONE
:NOPARAM
@set XVM=default
:RESOLVEDONE
@set NVWRAPPERLOGFILENAME=xvm.%XVM%.log
@rem Separate wrapper.* arguments from Main.java arguments
@set WRAPPER_PARAMS=
@if "!HAS_NAME_FLAG!"=="true" (
    @rem Name was explicitly provided via -n/-name, pass all args through
    @set APP_PARAMS="wrapper.app.parameter.1=--managed"
    @set PARAM_NUM=2
) else (
    @set APP_PARAMS="wrapper.app.parameter.1=-n" "wrapper.app.parameter.2=%XVM%" "wrapper.app.parameter.3=--managed"
    @set PARAM_NUM=4
)
:ARGLOOP
@if "%~1"=="" goto :ENDARGS
@set ARG=%~1
@if "!ARG:~0,8!"=="wrapper." (
    @set WRAPPER_PARAMS=!WRAPPER_PARAMS! "%~1"
) else (
    @set APP_PARAMS=!APP_PARAMS! "wrapper.app.parameter.!PARAM_NUM!=%~1"
    @set /a PARAM_NUM+=1
)
@shift
@goto :ARGLOOP
:ENDARGS
@goto :AFTERSCANSUB

@rem Subroutine to scan args for -n or -name
:SCANARGS
@if "%~1"=="" goto :SCANDONE
@if "%~1"=="-n" goto :FOUNDNAME
@if "%~1"=="-name" goto :FOUNDNAME
@shift
@goto :SCANARGS
:FOUNDNAME
@shift
@if "%~1"=="" goto :SCANDONE
@set XVM=%~1
@set HAS_NAME_FLAG=true
:SCANDONE
@goto :EOF

:AFTERSCANSUB
@call xwrapper -c %NVROOT%\conf\wrapper.server.conf %WRAPPER_PARAMS% %APP_PARAMS%
:DONE
@endlocal

