@echo off
setlocal enabledelayedexpansion

REM Define NGINX version, repo folder, and certificate paths
set "NGINX_VERSION=1.26.3"
set "NGINX_DOWNLOAD_URL=https://nginx.org/download/nginx-%NGINX_VERSION%.zip"
set "DOWNLOAD_FOLDER=%~dp0\tools\nginx_download"
set "NGINX_ZIP_PATH=%DOWNLOAD_FOLDER%\nginx-%NGINX_VERSION%.zip"
set "ABSSOLUTE_NDIR=C:\ABSSolute"
set "NGINX_INSTALL_PATH=C:\ABSSolute\Nginx_Infinity"
set "REPO_FOLDER=%~dp0\repo_infinity"

REM Get the IP address of the server
for /f "tokens=14 delims= " %%i in ('ipconfig ^| findstr /i "IPv4"') do set SERVER_IP=%%i
REM Display the IP address
echo The IP address of this server is: %SERVER_IP%

REM Prompt the user to enter a two-digit value for "xx" (01 to 99) for port configuration
set /p XX="Enter a value for 'slot' (01-99) for port configuration: "
if "%XX%" LSS "01" set XX=01
if "%XX%" GTR "99" set XX=99

set "NGINX_INSTALL_SLOT=%NGINX_INSTALL_PATH%_%XX%"

REM Main menu loop
:main_menu
cls
echo ============================================================================================
echo =                               NGINX and Application Manager                              =
echo = Option2 - will install Infinity on the server and will require Apache redirector link    =
echo = In Apache the load balance is done and backend redirector.                               =
echo = Option3 - will install Infinity on the server and it will create HTTP or HTTPS not both, =
echo = redirect in NginX. This will require backend link or links of the application server.    =
echo = The Infinity link that will be used will be the local one in NginX                       =
echo ============================================================================================
echo.
echo [1] Install NGINX with HTTPS and configure as a service
echo.
echo [2] Deploy Infinity application -- With Apache redirect --
echo [3] Deploy Infinity application -- Local with nginx redirect HTTP or HTTPS --
echo.
echo Start/Stop NGINX on selected slot %XX%
echo [4] Start NGINX service slot %XX%
echo [5] Stop NGINX service slot %XX%
echo.
echo [c] Update Custom Certificate
echo [u] Uninstall NGINX and Clear Installation
echo [0] Exit
echo ===========================================
set MENU_OPTION=
set /p MENU_OPTION="Choose an option (1-5,0,u): "

if "%MENU_OPTION%"=="1" goto install_nginx_https
if "%MENU_OPTION%"=="2" goto deploy_application
if "%MENU_OPTION%"=="3" goto deploy_application_local
if "%MENU_OPTION%"=="4" goto start_nginx_service
if "%MENU_OPTION%"=="5" goto stop_nginx_service
if "%MENU_OPTION%"=="c" goto update_nginx_certificates
if "%MENU_OPTION%"=="u" goto uninstall_nginx
if "%MENU_OPTION%"=="0" goto end_script

echo Invalid option. Please select 1, 2, 3, 4,5, u or 0.
pause
goto main_menu

REM ===========================================
REM Option 1: Install NGINX with HTTPS and configure service
REM ===========================================
:install_nginx_https
echo.
echo Installing NGINX version %NGINX_VERSION% with HTTPS...

REM Prompt the user to enter a two-digit value for "xx" (01 to 99) for port configuration
set /p XX="Enter a value for 'slot' (01-99) for port configuration: "
if "%XX%" LSS "01" set XX=01
if "%XX%" GTR "99" set XX=99

REM Check if NGINX is already installed
set "NGINX_INSTALL_SLOT=%NGINX_INSTALL_PATH%_%XX%"
if exist "%NGINX_INSTALL_SLOT%\nginx.exe" (
    echo NGINX is already installed.
	pause
    goto end_script
)

REM Set ports based on "xx" value
set "NGINX_HTTPS_PORT=5%XX%90"
set "STATUS_PORT=5%XX%93"
set "APP_HTTP_PORT=5%XX%91"
set "APP_HTTPS_PORT=5%XX%92"

REM Download NGINX if necessary
if not exist "%DOWNLOAD_FOLDER%" mkdir "%DOWNLOAD_FOLDER%"

echo Checking internet connectivity...
powershell -Command "if ((Invoke-WebRequest -Uri 'https://www.google.com' -UseBasicParsing).StatusCode -eq 200) { exit 0 } else { exit 1 }"
set "INTERNET_AVAILABLE=%errorlevel%"

if %INTERNET_AVAILABLE% equ 0 (
    echo Internet connection available. Downloading NGINX...
    powershell -Command "Invoke-WebRequest -Uri %NGINX_DOWNLOAD_URL% -OutFile '%NGINX_ZIP_PATH%'"

    REM Check if download was successful
    if not exist "%NGINX_ZIP_PATH%" (
        echo Failed to download NGINX.
        pause
        goto main_menu
    )
    set "DELETE_ZIP=1"
) else (
    echo No internet connection. Using local NGINX zip file...
    set "NGINX_ZIP_PATH=%~dp0\tools\nginx.zip"
    set "DELETE_ZIP=0"
)

REM Extract NGINX
set "CERTS_PATH=%NGINX_INSTALL_SLOT%\certs"
set "CONF_D_FOLDER=%NGINX_INSTALL_SLOT%\conf.d"
if not exist "%NGINX_INSTALL_SLOT%" mkdir "%NGINX_INSTALL_SLOT%"
echo Extracting NGINX...
powershell -Command "Expand-Archive -Path '%NGINX_ZIP_PATH%' -DestinationPath '%NGINX_INSTALL_PATH%' -Force"
echo Moving extracted files...
powershell -Command "Move-Item -Path '%NGINX_INSTALL_PATH%\nginx-%NGINX_VERSION%\*' -Destination '%NGINX_INSTALL_SLOT%'"
echo Cleaning up...
powershell -Command "Remove-Item -Path '%NGINX_INSTALL_PATH%' -Recurse -Force"

if %DELETE_ZIP% equ 1 (
    del "%NGINX_ZIP_PATH%"
)

REM Check if certificate exists, if not, generate a self-signed certificate
if not exist "%CERTS_PATH%\infinity.crt" (
    mkdir "%CERTS_PATH%"
    echo Generating self-signed SSL certificate...
    powershell -Command "New-SelfSignedCertificate -DnsName '%COMPUTERNAME%' -CertStoreLocation 'cert:\LocalMachine\My' | Export-PfxCertificate -FilePath '%CERTS_PATH%\infinity.pfx' -Password (ConvertTo-SecureString -String 'password' -Force -AsPlainText)"
    "%~dp0\tools\openssl\x64\bin"\openssl pkcs12 -in "%CERTS_PATH%\infinity.pfx" -nocerts -out "%CERTS_PATH%\infinity.key" -password pass:password -nodes
    "%~dp0\tools\openssl\x64\bin"\openssl pkcs12 -in "%CERTS_PATH%\infinity.pfx" -clcerts -nokeys -out "%CERTS_PATH%\infinity.crt" -password pass:password
)

REM Configure nginx.conf for HTTPS with dynamic port and include conf.d folder
set "NGINX_CONF=%NGINX_INSTALL_SLOT%\conf\nginx.conf"
set "CONF_D_PATH=
   REM Remove existing nginx.conf if it exists
if exist "%NGINX_CONF%" (
    del "%NGINX_CONF%"
)

REM Create new nginx.conf with the specified content
(
    echo #user  nobody;
    echo worker_processes  1;
    echo.
    echo #error_log  logs/error.log;
    echo #error_log  logs/error.log  notice;
    echo #error_log  logs/error.log  info;
    echo.
    echo pid        %ABSSOLUTE_NDIR%\Nginx_Infinity_%XX%\logs/nginx.pid;
    echo.
    echo events {
    echo     worker_connections  1024;
    echo }
    echo.
    echo http {
    echo     include       mime.types;
    echo     default_type  application/octet-stream;
    echo.
    echo     #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    echo     #                  '$status $body_bytes_sent "$http_referer" '
    echo     #                  '"$http_user_agent" "$http_x_forwarded_for"';
    echo.
    echo     #access_log  logs/access.log  main;
    echo.
    echo     sendfile        on;
    echo     #tcp_nopush     on;
    echo.
    echo     #keepalive_timeout  0;
    echo     keepalive_timeout  65;
    echo.
    echo     #gzip  on;
    echo.
    echo     include %ABSSOLUTE_NDIR%\Nginx_Infinity_%XX%\conf.d/*.conf;
    echo.
    echo     server {
    echo         listen %NGINX_HTTPS_PORT% ssl;
    echo         server_name %COMPUTERNAME%;
    echo         ssl_certificate "%CERTS_PATH%\infinity.crt";
    echo         ssl_certificate_key "%CERTS_PATH%\infinity.key";
    echo.
    echo         #charset koi8-r;
    echo.
    echo         #access_log  logs/host.access.log  main;
    echo.
    echo         location / {
    echo             root   html;
    echo             index  index.html index.htm;
    echo         }
    echo.
    echo         #error_page  404              /404.html;
    echo.
    echo         # redirect server error pages to the static page /50x.html
    echo         #
    echo         error_page   500 502 503 504  /50x.html;
    echo         location = /50x.html {
    echo             root   html;
    echo         }
    echo.
    echo         # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    echo         #
    echo         #location ~ \.php$ {
    echo         #    proxy_pass   http://127.0.0.1;
    echo         #}
    echo.
    echo         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    echo         #
    echo         #location ~ \.php$ {
    echo         #    root           html;
    echo         #    fastcgi_pass   127.0.0.1:9000;
    echo         #    fastcgi_index  index.php;
    echo         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    echo         #    include        fastcgi_params;
    echo         #}
    echo.
    echo         # deny access to .htaccess files, if Apache's document root
    echo         # concurs with nginx's one
    echo         #
    echo         #location ~ /\.ht {
    echo         #    deny  all;
    echo         #}
    echo     }
    echo.
    echo }
) > "%NGINX_CONF%"
    echo New nginx.conf created with HTTPS and status configuration.   
REM Debugging: Check if nginx.conf was created
if exist "%NGINX_CONF%" (
    echo New nginx.conf created successfully.
) else (
    echo Failed to create nginx.conf.
    pause
    goto main_menu
)

REM Create conf.d folder and generate status.conf
if not exist "%CONF_D_FOLDER%" mkdir "%CONF_D_FOLDER%"
(
    echo server {
    echo     listen %COMPUTERNAME%:%STATUS_PORT%;
    echo     server_name %COMPUTERNAME%;
    echo     location /nginx_status {
    echo         stub_status on;
    echo         access_log off;
    echo         allow %SERVER_IP%;
    echo         deny all;
    echo         }
    echo         location = /basic_status {
    echo             stub_status;
    echo             allow %SERVER_IP%;
    echo             allow ::1;
    echo             deny all;
    echo         }
    echo }
) > "%CONF_D_FOLDER%\stub_status.conf"

REM Install NGINX as a service using NSSM
set NSSM_URL=https://nssm.cc/release/nssm-2.24.zip
set NSSM_DIR=%NGINX_INSTALL_SLOT%\service
set service_name=ABS_NGinX_Infinity_%XX%

REM Create service directory if it doesn't exist
if not exist "%NSSM_DIR%" (
    mkdir "%NSSM_DIR%"
)

REM Install NSSM if it doesn't exist
if not exist "%NSSM_DIR%\nssm.exe" (
    echo Checking internet connectivity...
    powershell -Command "if ((Invoke-WebRequest -Uri 'https://www.google.com' -UseBasicParsing).StatusCode -eq 200) { exit 0 } else { exit 1 }"
    set "INTERNET_AVAILABLE=%errorlevel%"

    if %INTERNET_AVAILABLE% equ 0 (
        echo Internet connection available. Downloading NSSM...
        powershell -Command "Invoke-WebRequest -Uri '%NSSM_URL%' -OutFile '%NSSM_DIR%\nssm.zip'"
        echo Extracting NSSM...
        powershell -Command "Expand-Archive -Path '%NSSM_DIR%\nssm.zip' -DestinationPath '%NSSM_DIR%' -Force"
        powershell -Command "Copy-Item -Path '%NSSM_DIR%\nssm-2.24\win64\nssm.exe' -Destination '%NSSM_DIR%'"
        powershell -Command "Remove-Item -Path '%NSSM_DIR%\nssm-2.24' -Recurse -Force"
        powershell -Command "Remove-Item -Path '%NSSM_DIR%\nssm.zip' -Force"
    ) else (
        echo No internet connection. Extracting NSSM from local path...
        powershell -Command "Expand-Archive -Path '%~dp0\tools\nssm.zip' -DestinationPath '%NSSM_DIR%' -Force"
        powershell -Command "Copy-Item -Path '%NSSM_DIR%\nssm-2.24\win64\nssm.exe' -Destination '%NSSM_DIR%'"
        powershell -Command "Remove-Item -Path '%NSSM_DIR%\nssm-2.24' -Recurse -Force"
    )
)

set /p INSTALL_SERVICE="Do you want to install NGINX as a service? (y/n): "
if /i "%INSTALL_SERVICE%"=="y" (
    if not exist "%NSSM_DIR%\nssm.exe" (
        echo NSSM is required to run NGINX as a service. Please download it from https://nssm.cc/download.
        pause
        goto main_menu
    )

    %NSSM_DIR%\nssm.exe install %service_name% "%NGINX_INSTALL_SLOT%\nginx.exe"
    %NSSM_DIR%\nssm.exe start %service_name%
    echo NGINX has been set up and started as a service %service_name%.
    
    REM Check NGINX service status
    sc query %service_name%
    if %errorlevel% neq 0 (
        echo Service %service_name% is not running as expected.
        pause
    ) else (
        echo Service %service_name% is running successfully.
    )

) else (
    echo To run NGINX manually, go to "%NGINX_INSTALL_SLOT%" and execute "nginx.exe".
)
pause
goto main_menu


REM ===========================================
REM Option 2: Deploy Infinity application
REM ===========================================
:deploy_application
echo.
echo Deploying Infinity application...

REM Prompt the user to enter a two-digit value for "xx" (01 to 99) for port configuration
set /p XX="Enter a value for 'slot' (01-99) for port configuration: "
if "%XX%" LSS "01" set XX=01
if "%XX%" GTR "99" set XX=99

REM Set ports based on "xx" value
set "NGINX_HTTPS_PORT=5%XX%90"
set "STATUS_PORT=5%XX%93"
set "APP_HTTP_PORT=5%XX%91"
set "APP_HTTPS_PORT=5%XX%92"

set "NGINX_INSTALL_SLOT=%NGINX_INSTALL_PATH%_%XX%"
set "CERTS_PATH=%NGINX_INSTALL_SLOT%\certs"
set "CONF_D_FOLDER=%NGINX_INSTALL_SLOT%\conf.d"

REM Delete the apps folder quietly at the beginning of the script
rd /S /Q "%NGINX_INSTALL_SLOT%\html\apps"

REM Check for available versions in repo_infinity
setlocal enabledelayedexpansion
set count=0
for %%f in ("%REPO_FOLDER%\*.zip") do (
    set /a count+=1
    set "VERSION_!count!=%%~nf"  
    set "FILE_!count!=%%~nxf"
    echo [!count!] %%~nf
)
if %count%==0 (
    echo No application versions found in %REPO_FOLDER%.
    pause
    goto main_menu
)

REM Prompt user to select version
set /p VERSION_CHOICE="Select a version number by entering its corresponding number (1-%count%): "
if %VERSION_CHOICE% LSS 1 (
    echo Invalid selection.
    pause
    goto main_menu
) else if %VERSION_CHOICE% GTR %count% (
    echo Invalid selection.
    pause
    goto main_menu
)

REM Extract and deploy selected application version
set "SELECTED_VERSION=!VERSION_%VERSION_CHOICE%!"
set "APP_ZIP=%REPO_FOLDER%\%SELECTED_VERSION%.zip"
echo You selected version %SELECTED_VERSION%.

REM Extract application into NGINX folder
echo Extracting application version %SELECTED_VERSION%...
powershell -Command "Expand-Archive -Path '%APP_ZIP%' -DestinationPath '%NGINX_INSTALL_SLOT%\html' -Force"
echo Application version %SELECTED_VERSION% deployed successfully.

REM Modify absConfig.json based on user input
set "CONFIG_DIR=%NGINX_INSTALL_SLOT%\html\apps\abs-root\assets\general\config"
set "SAMPLE_CONFIG=%CONFIG_DIR%\sample_absConfig.json"
set "ABS_CONFIG=%CONFIG_DIR%\absConfig.json"

REM Prompt user for the HTTP or HTTPS link
set /p new_url="Enter the new URL HTTP or HTTPS link e.g. https://abs.abssolute.net: "

:: Read the JSON file and replace the URL
(for /f "tokens=*" %%i in (%SAMPLE_CONFIG%) do (
    set "line=%%i"
    set "line=!line:http://rdwebl-buc.internal.abslbs.com:53217=%new_url%!"
    echo !line!
)) > %ABS_CONFIG%
echo Created absConfig.json from sample_absConfig.json with %new_url%

REM Prompt user for peripheralAgentSecureConnection value
set /p secure_connection="Enable peripheralAgentSecureConnection? (true/false, leave empty to keep current): "

REM If user entered a value, replace "false" or "true" with the new input
if not "%secure_connection%"=="" (
    powershell -Command "(Get-Content '%ABS_CONFIG%') -replace '\"peripheralAgentSecureConnection\":\s*(true|false)', '\"peripheralAgentSecureConnection\": %secure_connection%' | Set-Content '%ABS_CONFIG%'"
    echo Updated peripheralAgentSecureConnection to %secure_connection%.
) else (
    echo No changes made to peripheralAgentSecureConnection.
)

REM Create conf.d folder and generate infinity_xx.conf
if not exist "%CONF_D_FOLDER%" mkdir "%CONF_D_FOLDER%"
(
    echo server {
    echo   listen       %APP_HTTPS_PORT% ssl;
    echo   server_name  %COMPUTERNAME% %SERVER_IP%;
    echo. 
    echo   ssl_certificate %CERTS_PATH%\infinity.crt;
    echo   ssl_certificate_key %CERTS_PATH%\infinity.key;
    echo. 
	echo   ssl_protocols TLSv1.2 TLSv1.3;
    echo   ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305";
    echo   ssl_session_cache shared:SSL:10m;
    echo   ssl_session_timeout 10m;
    echo   ssl_prefer_server_ciphers on;
    echo. 
    echo   location / {
    echo     root        %NGINX_INSTALL_SLOT%\html\apps\abs-root;
    echo     try_files $uri $uri/ /index.html$is_args$args;
    echo     index       index.html index.htm;
    echo     expires     -1;
    echo     add_header  Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
    echo   }
    echo }
    echo. 
    echo server {
    echo   listen       %APP_HTTP_PORT%;
    echo   server_name  %COMPUTERNAME% %SERVER_IP%;
    echo. 
    echo   location / {
    echo     root        %NGINX_INSTALL_SLOT%\html\apps\abs-root;
    echo     try_files $uri $uri/ /index.html$is_args$args;
    echo     index       index.html index.htm;
    echo     expires     -1;
    echo     add_header  Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
    echo   }
    echo }
) > "%CONF_D_FOLDER%\infinity_%XX%.conf"

echo Configuration for application ports %APP_HTTP_PORT% (HTTP) and %APP_HTTPS_PORT% (HTTPS) saved to conf.d/infinity_%XX%.conf.

REM Automatically restart NGINX after installation
goto restart_nginx
pause

goto main_menu

REM ================================================================
REM Option 3: Deploy Infinity application localy with NginX redirect
REM ================================================================
:deploy_application_local
echo.
echo Deploying Infinity application...

REM Prompt the user to enter a two-digit value for "xx" (01 to 99) for port configuration
set /p XX="Enter a value for 'slot' (01-99) for port configuration: "
if "%XX%" LSS "01" set XX=01
if "%XX%" GTR "99" set XX=99

REM Set ports based on "xx" value
set "NGINX_HTTPS_PORT=5%XX%90"
set "STATUS_PORT=5%XX%93"
set "APP_HTTP_PORT=5%XX%91"
set "APP_HTTPS_PORT=5%XX%92"

set "NGINX_INSTALL_SLOT=%NGINX_INSTALL_PATH%_%XX%"
set "CERTS_PATH=%NGINX_INSTALL_SLOT%\certs"
set "CONF_D_FOLDER=%NGINX_INSTALL_SLOT%\conf.d"

REM Delete the apps folder quietly at the beginning of the script
rd /S /Q "%NGINX_INSTALL_SLOT%\html\apps"

REM Check for available versions in repo_infinity
setlocal enabledelayedexpansion
set count=0
for %%f in ("%REPO_FOLDER%\*.zip") do (
    set /a count+=1
    set "VERSION_!count!=%%~nf"  
    set "FILE_!count!=%%~nxf"
    echo [!count!] %%~nf
)

if %count%==0 (
    echo No application versions found in %REPO_FOLDER%.
    pause
    goto main_menu
)

REM Prompt user to select version
set /p VERSION_CHOICE="Select a version number by entering its corresponding number (1-%count%): "
if %VERSION_CHOICE% LSS 1 (
    echo Invalid selection.
    pause
    goto main_menu
) else if %VERSION_CHOICE% GTR %count% (
    echo Invalid selection.
    pause
    goto main_menu
)

REM Extract and deploy selected application version
set "SELECTED_VERSION=!VERSION_%VERSION_CHOICE%!"
set "APP_ZIP=%REPO_FOLDER%\%SELECTED_VERSION%.zip"
echo You selected version %SELECTED_VERSION%.

REM Extract application into NGINX folder
echo Extracting application version %SELECTED_VERSION%...
powershell -Command "Expand-Archive -Path '%APP_ZIP%' -DestinationPath '%NGINX_INSTALL_SLOT%\html' -Force"
echo Application version %SELECTED_VERSION% deployed successfully.

REM Modify absConfig.json based on user input
set "CONFIG_DIR=%NGINX_INSTALL_SLOT%\html\apps\abs-root\assets\general\config"
set "SAMPLE_CONFIG=%CONFIG_DIR%\sample_absConfig.json"
set "ABS_CONFIG=%CONFIG_DIR%\absConfig.json"

REM Prompt user for HTTP or HTTPS configuration
set /p config_choice="Choose your configuration connection -http- or -https-: "
if /i "%config_choice%"=="https" (
    set HTTPS_ENABLED=1
) else if /i "%config_choice%"=="http" (
    set HTTPS_ENABLED=0
) else (
    echo Invalid choice. Please enter either "http" or "https".
    exit /b
)

REM Prompt user for the HTTP or HTTPS link
set /p new_url="Enter the local server URL -HTTP- or -HTTPS- link (e.g. leave blank to use %config_choice%://%COMPUTERNAME%:%APP_HTTPS_PORT%): "

REM Set default if user input is empty
if "%new_url%"=="" (
    set "new_url=%config_choice%://%COMPUTERNAME%:%APP_HTTPS_PORT%"
)

REM Enable delayed expansion for safe replacement
setlocal enabledelayedexpansion

:: Read the JSON file and replace the URL
(
    for /f "usebackq tokens=*" %%i in ("%SAMPLE_CONFIG%") do (
        set "line=%%i"
        set "line=!line:http://rdwebl-buc.internal.abslbs.com:53217=%new_url%!"
        echo(!line!
    )
) > "%ABS_CONFIG%"

endlocal
echo Created absConfig.json from sample_absConfig.json with %new_url%

REM Prompt user for peripheralAgentSecureConnection value
set /p secure_connection="Enable peripheralAgentSecureConnection? (true/false, leave empty to keep current): "

REM If user entered a value, replace "false" or "true" with the new input
if not "%secure_connection%"=="" (
    powershell -Command "(Get-Content '%ABS_CONFIG%') -replace '\"peripheralAgentSecureConnection\":\s*(true|false)', '\"peripheralAgentSecureConnection\": %secure_connection%' | Set-Content '%ABS_CONFIG%'"
    echo Updated peripheralAgentSecureConnection to %secure_connection%.
) else (
    echo No changes made to peripheralAgentSecureConnection.
)

REM Prompt user for application servers
set /p APPServer1="Enter the first application server (e.g., rds-buc.internal.abslbs.com:50117): "
set /p APPServer2="Enter the second application server (or leave blank if not present): "

REM If the user left APPServer2 blank, set it to APPServer1
if "%APPServer2%"=="" set APPServer2=%APPServer1%

REM Create conf.d folder if it doesn't exist
if not exist "%CONF_D_FOLDER%" mkdir "%CONF_D_FOLDER%"

REM Generate infinity_xx.conf based on user choice
(
    REM Define backend endpoint dynamically based on user input
    echo upstream backend_endpoint {
    echo    server %APPServer1%;
    echo    server %APPServer2%;
    echo }
    echo.

    if %HTTPS_ENABLED%==1 (
        echo server {
        echo   listen       %APP_HTTPS_PORT% ssl;
        echo   server_name  %COMPUTERNAME% %SERVER_IP%;
        echo. 
        echo   ssl_certificate %CERTS_PATH%\infinity.crt;
        echo   ssl_certificate_key %CERTS_PATH%\infinity.key;
        echo. 
        echo   ssl_protocols TLSv1.2 TLSv1.3;
        echo   ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305";
        echo   ssl_session_cache shared:SSL:10m;
        echo   ssl_session_timeout 10m;
        echo   ssl_prefer_server_ciphers on;
        echo. 
        echo   location / {
        echo     root        %NGINX_INSTALL_SLOT%\html\apps\abs-root;
        echo     try_files $uri $uri/ /index.html$is_args$args;
        echo     index       index.html index.htm;
        echo     expires     -1;
        echo     add_header  Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        echo   }
        echo.
        echo   proxy_ssl_verify off;
        echo   proxy_set_header Host $host;
        echo   proxy_set_header X-Real-IP $remote_addr;
        echo   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        echo   proxy_set_header X-Forwarded-Proto $scheme;
        echo   proxy_set_header X-NginX-Proxy true;
        echo   proxy_max_temp_file_size 0;
        echo.
        echo   # Proxy routes to backend
        echo   location /client {
        echo       proxy_pass https://backend_endpoint;
        echo       proxy_redirect off;
        echo   }
        echo. 
        echo   location /authentication {
        echo       proxy_pass https://backend_endpoint;
        echo       proxy_redirect off;
        echo   }
        echo. 
        echo   location /monitoring {
        echo       proxy_pass https://backend_endpoint;
        echo       proxy_next_upstream error timeout http_502 http_503 http_504;
        echo       proxy_connect_timeout 5s;
        echo       proxy_read_timeout 5s;
        echo       proxy_redirect off;
        echo   }
        echo. 
        echo   location /printing {
        echo       proxy_pass https://backend_endpoint;
        echo       proxy_redirect off;
        echo   }
        echo. 
        echo   location /localPrintServer {
        echo       proxy_pass https://backend_endpoint;
        echo       proxy_redirect off;
        echo   }
        echo }
    ) else (
        echo server {
        echo   listen       %APP_HTTP_PORT%;
        echo   server_name  %COMPUTERNAME% %SERVER_IP%;
        echo. 
        echo   location / {
        echo     root        %NGINX_INSTALL_SLOT%\html\apps\abs-root;
        echo     try_files $uri $uri/ /index.html$is_args$args;
        echo     index       index.html index.htm;
        echo     expires     -1;
        echo     add_header  Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        echo   }
        echo.
        echo   proxy_set_header Host $host;
        echo   proxy_set_header X-Real-IP $remote_addr;
        echo   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        echo   proxy_set_header X-Forwarded-Proto $scheme;
        echo   proxy_set_header X-NginX-Proxy true;
        echo   proxy_max_temp_file_size 0;
        echo.
        echo   # Proxy routes to backend
        echo   location /client {
        echo       proxy_pass http://backend_endpoint;
        echo       proxy_redirect off;
        echo   }
        echo.
        echo   location /authentication {
        echo       proxy_pass http://backend_endpoint;
        echo       proxy_redirect off;
        echo   }
        echo.
        echo   location /monitoring {
        echo       proxy_pass http://backend_endpoint;
	    echo       proxy_next_upstream error timeout http_502 http_503 http_504;
        echo       proxy_connect_timeout 5s;
        echo       proxy_read_timeout 5s;
        echo       proxy_redirect off;
        echo   }
        echo.
        echo   location /printing {
        echo       proxy_pass http://backend_endpoint;
        echo       proxy_redirect off;
        echo   }
        echo.
        echo   location /localPrintServer {
        echo       proxy_pass http://backend_endpoint;
        echo       proxy_redirect off;
        echo   }
        echo }
    )
) > "%CONF_D_FOLDER%\infinity_%XX%.conf"

echo Configuration saved to conf.d/infinity_%XX%.conf with HTTPS_ENABLED=%HTTPS_ENABLED%.

pause
goto update_nginx_certificates

REM ===========================================
REM Update Custom Certificate
REM ===========================================
:update_nginx_certificates
echo.
echo Updating custom nginx certificates...

set "NGINX_INSTALL_SLOT=%NGINX_INSTALL_PATH%_%XX%"
set "CERTS_PATH=%NGINX_INSTALL_SLOT%\certs"

REM Create the certs directory if it doesn't exist
if not exist "%CERTS_PATH%" mkdir "%CERTS_PATH%"

REM Find certificate and key in the script's cert folder
set "CERT_SOURCE_DIR=%~dp0cert"
set "CRT_FILE="
set "KEY_FILE="

for %%f in ("%CERT_SOURCE_DIR%\*.crt") do (
    if not defined CRT_FILE set "CRT_FILE=%%f"
)

for %%f in ("%CERT_SOURCE_DIR%\*.key") do (
    if not defined KEY_FILE set "KEY_FILE=%%f"
)

REM Copy cert and key if both are found
if defined CRT_FILE if defined KEY_FILE (
    echo Found certificate and key files. Copying to %CERTS_PATH%...
    copy /Y "%CRT_FILE%" "%CERTS_PATH%\infinity.crt" >nul
    copy /Y "%KEY_FILE%" "%CERTS_PATH%\infinity.key" >nul
    echo Certificates updated successfully!
) else (
    echo No custom certificate found. Continuing...
)

REM Automatically restart NGINX after installation
goto restart_nginx
pause
goto main_menu


REM ===========================================
REM Restart NGINX service
REM ===========================================
:restart_nginx
set "service_name=ABS_NGinX_Infinity_%XX%"
sc stop %service_name%
if %errorlevel% neq 0 (
    echo Failed to stop the NGINX service %service_name%.
    pause
) else (
    echo NGINX service %service_name% stopped successfully.
    pause
)
timeout /t 3 /nobreak

sc start %service_name%
if %errorlevel% neq 0 (
    echo Failed to start the NGINX service %service_name%.
    pause
) else (
    echo NGINX service %service_name% started successfully.
    pause
)

goto main_menu

REM ===========================================
REM Option 4: Start NGINX service
REM ===========================================
:start_nginx_service
echo.
echo Starting NGINX service...

REM Define the service name (assuming it’s consistently named based on the slot value)
set "service_name=ABS_NGinX_Infinity_%XX%"

sc start %service_name%
if %errorlevel% neq 0 (
    echo Failed to start the NGINX service %service_name%.
    pause
) else (
    echo NGINX service %service_name% started successfully.
    pause
)

goto main_menu

REM ===========================================
REM Option 5: Stop NGINX service
REM ===========================================
:stop_nginx_service
echo.
echo Stopping NGINX service...

REM Define the service name
set "service_name=ABS_NGinX_Infinity_%XX%"

sc stop %service_name%
if %errorlevel% neq 0 (
    echo Failed to stop the NGINX service %service_name%.
    pause
) else (
    echo NGINX service %service_name% stopped successfully.
    pause
)

goto main_menu

REM ===========================================
REM Option u: Uninstall NGINX and Clear Installation
REM ===========================================
:uninstall_nginx
REM Prompt the user to enter a two-digit value for "xx" (01 to 99) for port configuration
set /p XX="Enter a value for 'slot' (01-99) for port configuration: "
if "%XX%" LSS "01" set XX=01
if "%XX%" GTR "99" set XX=99
set "NGINX_INSTALL_SLOT=%NGINX_INSTALL_PATH%_%XX%"

REM Set ports based on "xx" value
set "NGINX_HTTPS_PORT=5%XX%90"
set "STATUS_PORT=5%XX%93"
set "APP_HTTP_PORT=5%XX%91"
set "APP_HTTPS_PORT=5%XX%92"

set service_name=ABS_NGinX_Infinity_%XX%
echo Uninstalling NGINX service and clearing installation...

REM Stop the service if it is running
sc query %service_name% | findstr /i "RUNNING"
if %errorlevel% equ 0 (
    echo Stopping the NGINX service...
    sc stop %service_name%
    if %errorlevel% neq 0 (
        echo Failed to stop the service. Continuing with uninstallation.
    )
)

REM Delete the service
sc delete %service_name%
if %errorlevel% neq 0 (
    echo Failed to delete the service %service_name%.
) else (
    echo Service %service_name% deleted successfully.
)

timeout /t 3 /nobreak

REM Remove NGINX installation directory
if exist "%NGINX_INSTALL_SLOT%" (
    echo Deleting NGINX installation directory: %NGINX_INSTALL_SLOT%...
    rmdir /s /q "%NGINX_INSTALL_SLOT%"
    if %errorlevel% neq 0 (
        echo Failed to delete the installation directory %NGINX_INSTALL_SLOT%.
    ) else (
        echo NGINX installation directory deleted successfully.
    )
)

echo Uninstallation complete.
pause
goto main_menu

REM ===========================================
REM Exit script
REM ===========================================
:end_script
echo Exiting...
endlocal
exit /b
