setlocal enabledelayedexpansion

textreplace -std -t bin\qgis-ltr-dev.bat
textreplace -std -t bin\qgis-ltr-dev-designer.bat
textreplace -std -t bin\python-qgis-ltr-dev.bat
textreplace -std -t bin\qgis_process-qgis-ltr-dev.bat

if "%OSGEO4W_DESKTOP%"=="" set OSGEO4W_DESKTOP=~$folder.common_desktop$

if not %OSGEO4W_MENU_LINKS%==0 mkdir "%OSGEO4W_STARTMENU%"
if not %OSGEO4W_DESKTOP_LINKS%==0 mkdir "%OSGEO4W_DESKTOP%"

call "%OSGEO4W_ROOT%\bin\qgis-ltr-dev.bat" --postinstall

if not %OSGEO4W_MENU_LINKS%==0 nircmd shortcut "%OSGEO4W_ROOT%\bin\qgis-ltr-dev-bin.exe" "%OSGEO4W_STARTMENU%" "QGIS Desktop 3.16.7" "" "" "" "" "~$folder.mydocuments$"
if not %OSGEO4W_DESKTOP_LINKS%==0 nircmd shortcut "%OSGEO4W_ROOT%\bin\qgis-ltr-dev-bin.exe" "%OSGEO4W_DESKTOP%" "QGIS Desktop 3.16.7" "" "" "" "" "~$folder.mydocuments$"

for %%g in (grass78) do (
	set gv=
	for /f "usebackq tokens=1" %%a in (`%%g --config version`) do set gv=%%a
	if not "!gv!"=="" (
		for /F "delims=." %%i in ("!gv!") do set v=%%i

		copy "%OSGEO4W_ROOT%\bin\qgis-ltr-dev-bin.exe" "%OSGEO4W_ROOT%\bin\qgis-ltr-dev-bin-g!v!.exe"
		copy "%OSGEO4W_ROOT%\bin\qgis-ltr-dev-bin.vars" "%OSGEO4W_ROOT%\bin\qgis-ltr-dev-bin-g!v!.vars"
		textreplace -std -map @grassmajor@ !v! -t bin\qgis-ltr-dev-g!v!.bat
		call "%OSGEO4W_ROOT%\bin\qgis-ltr-dev-g!v!.bat" --postinstall

		if not %OSGEO4W_MENU_LINKS%==0 nircmd shortcut "%OSGEO4W_ROOT%\bin\qgis-ltr-dev-bin-g!v!.exe" "%OSGEO4W_STARTMENU%" "QGIS Desktop 3.16.7 with GRASS !gv! (Nightly)" "" "" "" "" "~$folder.mydocuments$"
		if not %OSGEO4W_DESKTOP_LINKS%==0 nircmd shortcut "%OSGEO4W_ROOT%\bin\qgis-ltr-dev-bin-g!v!.exe" "%OSGEO4W_DESKTOP%" "QGIS Desktop 3.16.7 with GRASS !gv! (Nightly)" "" "" "" "" "~$folder.mydocuments$"
	)
)

if not %OSGEO4W_MENU_LINKS%==0 nircmd shortcut "%OSGEO4W_ROOT%\bin\nircmd.exe" "%OSGEO4W_STARTMENU%" "Qt Designer with QGIS 3.16.7 custom widgets (Nightly)" "exec hide """%OSGEO4W_ROOT%\bin\qgis-ltr-dev-designer.bat"" "%OSGEO4W_ROOT%\apps\qgis-ltr-dev\icons\QGIS.ico" "" "" "~$folder.mydocuments$"
if not %OSGEO4W_DESKTOP_LINKS%==0 nircmd shortcut "%OSGEO4W_ROOT%\bin\nircmd.exe" "%OSGEO4W_DESKTOP%" "Qt Designer with QGIS 3.16.7 custom widgets (Nightly)" "exec hide """%OSGEO4W_ROOT%\bin\qgis-ltr-dev-designer.bat"" "%OSGEO4W_ROOT%\apps\qgis-ltr-dev\icons\QGIS.ico" "" "" "~$folder.mydocuments$"

set O4W_ROOT=%OSGEO4W_ROOT%
set OSGEO4W_ROOT=%OSGEO4W_ROOT:\=\\%
textreplace -std -t "%O4W_ROOT%\apps\qgis-ltr-dev\bin\qgis.reg"
set OSGEO4W_ROOT=%O4W_ROOT%

REM Do not register extensions if release is installed
if not exist "%O4W_ROOT%\apps\qgis\bin\qgis.reg" nircmd elevate "%WINDIR%\regedit" /s "%O4W_ROOT%\apps\qgis-ltr-dev\bin\qgis.reg"

call "%OSGEO4W_ROOT%\bin\o4w_env.bat"
call qt5_env.bat
call gdal-dev-env.bat
path %PATH%;%OSGEO4W_ROOT%\apps\qgis-ltr-dev\bin
set QGIS_PREFIX_PATH=%OSGEO4W_ROOT:\=/%/apps/qgis-ltr-dev
"%OSGEO4W_ROOT%\apps\qgis-ltr-dev\crssync"

del /s /q "%OSGEO4W_ROOT%\apps\qgis-ltr-dev\*.pyc"
exit /b 0

endlocal
