@echo off

call :check_gsqlcmd
call :get_application_label

call :execute_file  savetodb-framework-list.sql         "SaveToDB Framework"
call :execute_file  change-tracking-framework-list.sql  "Change Tracking Framework"
call :execute_file  database-help-framework-list.sql    "Database Help Framework"
call :execute_file  application-list.sql                "%label%"

pause

goto :EOF


:execute_file

if .%1.==.. goto :EOF

set file=?

if exist sources\%1 set file=sources\%1
if exist %1         set file=%1

if .%file%.==.?. goto :EOF

echo %~2
gsqlcmd execute setup %file% /inputcodepage=65001 /notransaction

if errorlevel 1 (
    echo.
    echo Fatal error of executing %file%
    pause
    exit
)

echo.

goto :EOF


:check_gsqlcmd

gsqlcmd connections>nul 2>nul

if errorlevel 1 (
    echo.
    echo Install the gsqlcmd command-line tool to use batch files.
    echo.
    echo Download it at https://www.gsqlcmd.com
    pause
    exit
)

goto :EOF


:get_application_label

set label=?

if exist label.txt @for /F "delims==" %%i in (label.txt) do set label=%%i

if not "%label%"=="?" goto :EOF

if exist sources\application-install.sql (
    for %%i in (.) do set label=%%~nxi
) else if exist sources\application-install.sql (
    for %%i in (.) do set label=%%~nxi
) else (
    if exist sources\savetodb-framework-install-en.sql              set label=SaveToDB Framework 7
    if exist sources\savetodb-framework-install.sql                 set label=SaveToDB Framework
    if exist sources\savetodb-developer-framework-install.sql       set label=SaveToDB Developer Framework
    if exist sources\savetodb-administrator-framework-install.sql   set label=SaveToDB Administrator Framework
    if exist sources\change-tracking-framework-install.sql          set label=Change Tracking Framework
    if exist sources\database-help-framework-install.sql            set label=Database Help Framework

    if exist savetodb-framework-install-en.sql                      set label=SaveToDB Framework 7
    if exist savetodb-framework-install.sql                         set label=SaveToDB Framework
    if exist savetodb-developer-framework-install.sql               set label=SaveToDB Developer Framework
    if exist savetodb-administrator-framework-install.sql           set label=SaveToDB Administrator Framework
    if exist change-tracking-framework-install.sql                  set label=Change Tracking Framework
    if exist database-help-framework-install.sql                    set label=Database Help Framework

    if not "%label%"=="?" goto :EOF

    for %%i in (.) do set label=%%~nxi
)

goto :EOF

:END
