@echo off

set CHAIN=mainnet

setlocal enabledelayedexpansion

goto :main

:main
    call :parse_args %*

    if "%CHAIN%" == "mainnet" (
        if not defined NODE_PORT set NODE_PORT=8676
        if not defined RPC_PORT set RPC_PORT=8677
    ) else if "%CHAIN%"=="testnet" (
        if not defined NODE_PORT set NODE_PORT=18676
        if not defined RPC_PORT set RPC_PORT=18677
    ) else (
        if not defined NODE_PORT set NODE_PORT=18888
        if not defined RPC_PORT set RPC_PORT=18889
    )

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

    set RELEASE_DIR=%ABEC_RELEASE_HOME%
    set PROG="%RELEASE_DIR%\abec"
    set DATA_DIR=%USER_DATA_DIR%\Abec
    set WORK_DIR=%DATA_DIR%

    set CHAIN_OPTS=
    if "%CHAIN%" == "testnet" (
        set CHAIN_OPTS=--testnet --addpeer=ec2-34-227-111-24.compute-1.amazonaws.com:18666
    ) else if "%CHAIN%" == "simnet" (
        set CHAIN_OPTS=--simnet --addpeer=abec-service-simnet-0.abelos.io:18888 --addpeer=abec-service-simnet-1.abelos.io:18888 --addpeer=abec-service-simnet-2.abelos.io:18888
    )
    IF NOT "%ADD_CHECK_POINT%"=="" (
        set CHAIN_OPTS=%CHAIN_OPTS% --addcheckpoint=%ADD_CHECK_POINT%
    )

    set ABEC_DO_NOT_ASK_FOR_NODE_TYPE_CHANGE=true

    set "ABEC_DIR=%LOCALAPPDATA%\Abec"
    set "ABEC_CONF=%ABEC_DIR%\abec.conf"
    if not exist "%ABEC_CONF%" (
        if not exist "%ABEC_DIR%" (
            mkdir "%ABEC_DIR%"
        )
        (echo. 2> NUL) > "%ABEC_CONF%"
    )

    %PROG% ^
        --nodetype=normalnode ^
        --datadir="%DATA_DIR%" ^
        --logdir="%DATA_DIR%/logs" ^
        --notls --rpcuser="localuser" --rpcpass="localpass" ^
        --listen=0.0.0.0:%NODE_PORT% ^
        --rpclisten=127.0.0.1:%RPC_PORT% ^
        --txindex ^
        %CHAIN_OPTS% 2>NUL 1>NUL

    EXIT /B

:usage
    echo Usage: %0 [-c CHAIN(mainnet^|testnet^|simnet)] [-p NODE_PORT] [-r RPC_PORT] [-a ADD_CHECK_POINT] [-w ABEC_MAX_RESERVED_WITNESS]
    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 NODE_PORT=%%i
        if !next_line! == "-r" set RPC_PORT=%%i
        if !next_line! == "-a" set ADD_CHECK_POINT=%%i
        if !next_line! == "-w" set ABEC_MAX_RESERVED_WITNESS=%%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" == "-w" (
            set next_line = "-w"
        ) else (
            set next_line=
        )
    )


endlocal