@echo off

set CHAIN=
set ABEC_RPC_PORT=
set RPC_PORT=
set ACCOUNT=
set PUB_PASS=

setlocal enabledelayedexpansion

goto :main

:main
    call :parse_args %*
    if "%CHAIN%" == "" if "%ACCOUNT%" == "" if %PUB_PASS% == "" goto :exit_abnormal

    if "%CHAIN%" == "mainnet" (
        if not defined ABEC_RPC_PORT set ABEC_RPC_PORT=8677
        if not defined RPC_PORT set RPC_PORT=8675
    ) else (
        if not defined ABEC_RPC_PORT set ABEC_RPC_PORT=18677
        if not defined RPC_PORT set RPC_PORT=18675
    )

    if defined ABELWALLET_HOME (
        set "USER_DATA_DIR=%ABELWALLET_HOME%"
    ) else (
        set "USER_DATA_DIR=%APPDATA%\Abelian Wallet"
    )

    set RELEASE_DIR=%ABEWALLET_RELEASE_HOME%
    set PROG="%RELEASE_DIR%\abewallet"
    set WALLET_DATA_DIR=%USER_DATA_DIR%\Abewallet\%ACCOUNT%

    set CHAIN_OPTS=
    if "%CHAIN%" == "testnet" (
        set CHAIN_OPTS=--testnet
    ) else if "%CHAIN%" == "simnet" (
        set CHAIN_OPTS=--simnet
    )

    set "ABEWALLET_CONF=%WALLET_DATA_DIR%\abewallet.conf"
    if not exist "%ABEWALLET_CONF%" (
        (echo. 2> NUL) > "%ABEWALLET_CONF%"
    )

    %PROG% ^
        --appdata="%WALLET_DATA_DIR%" ^
        --logdir="%WALLET_DATA_DIR%" ^
        --noclienttls --noservertls ^
        --abecrpcuser="localuser" --abecrpcpass="localpass" ^
        --rpcuser="localuser" --rpcpass="localpass" ^
        --walletpass="%PUB_PASS%" ^
        --rpclisten=127.0.0.1:%RPC_PORT% ^
        --rpcconnect=127.0.0.1:%ABEC_RPC_PORT% ^
        %CHAIN_OPT% 2>NUL 1>NUL

    EXIT /B

:usage
    echo Usage: %0 -c CHAIN(mainnet^|testnet^|simnet) [-p ABEC_RPC_PORT] [-r RPC_PORT]
    echo    -a ACCOUNT -y PUBLIC_PASSPHRASE
    goto :EOF

:exit_abnormal
    call :usage
    exit /b 1

:parse_args
    set next_line=

    for %%i in (%*) do (
        if !next_line! == "-c" (
            set CHAIN=%%i
            if not "!CHAIN!"=="mainnet" if not "!CHAIN!"=="testnet" if not "!CHAIN!"=="simnet" goto exit_abnormal
        )
        if !next_line! == "-p" set ABEC_RPC_PORT=%%i
        if !next_line! == "-r" set RPC_PORT=%%i
        if !next_line! == "-a" set ACCOUNT=%%i
        if !next_line! == "-y" set PUB_PASS=%%i

        if "%%i" == "-c" (
            set next_line="-c"
        ) else if "%%i" == "-p" (
            set next_line="-p"
        ) else if "%%i" == "-r" (
            set next_line="-r"
        ) else if "%%i" == "-a" (
            set next_line="-a"
        ) else if "%%i" == "-y" (
            set next_line="-y"
        ) else (
            set next_line=
        )
    )


endlocal