@echo off
setlocal enableextensions enabledelayedexpansion
cls
set tbwinre_ver=1.12

echo.
echo ==============================================================================
echo   TeraByte WinRE Builder                                           ver. %tbwinre_ver%
echo ==============================================================================
echo.


:: ===============================================================
:: ====================== Set Custom Paths =======================

:: Note: Set these paths only if not using the default installation paths. 
:: Do not include a trailing backslash. Do not include any spaces before or after the equals sign.
:: Example: set ifwpath=D:\TeraByte\Image for Windows

set ifwpath=

set tbiviewpath=

set tbosdtpath=

:: ===============================================================
:: ====================== Set Build Options ======================

:: Use this option to set the build mode used by the script:
:: 0 = Ask user for mode when run. This is the default setting
:: 1 = Modify the Windows Recovery Environment (WinRE) accessed via F8
::       when booting (Windows 7) or the Boot/Restart menu (Windows 8)
:: 2 = Create a TBWinRE CD, USB Flash Drive (UFD), or ISO file
:: 3 = Restore the original WinRE.WIM file (use this mode to return the
::       Recovery Environment to its original state)
:: 4 = Create boot file TBWinRE.bin for use with TeraByte's BOOTFILE program
set buildmode=0

:: Use this option to change the screen resolution used by WinRE. The default
:: resolution is 1024x768 (-m3). For resolution options, run chgres.
set screenresolution=-m3

:: If pausebuild=1 the build will pause before unmounting the WIM file. This allows
:: advanced users to verify content or add content before build completes.
:: Set to 0 (zero) to cancel pausing.
set pausebuild=0

:: If usestartnetcmd=1 the build will use the startnet.cmd file to control program startup
:: instead of the default (winpeshl.ini).
:: Set to 0 (zero) to use the default.
set usestartnetcmd=0

:: Use this option to set the input locale to an alternate value. The locale
:: selected must be supported by the current language being used.
:: Example: set inputlocale=fr-CH
set inputlocale=

:: Use this option set the screen DPI value. This can be helpful when using
:: FHD/QHD/QFHD displays that are not automatically detected correctly.
:: Default DPI will be used if option not set or specified value is invalid.
:: Set to 0 (zero) or leave blank to use the default.
:: Valid values are: 0, 96, 120, 144, 192
set screendpi=0


:: ===============================================================
:: ===============================================================
:: ============ Don't Change Anything Below This Line ============


:: --------------------
:: Set Paths & Variables
::
set tbpath=%~dp0
set tbpath=%tbpath:~0,-1%
cd /d "%tbpath%"

set PATH=%SystemRoot%;%SystemRoot%\System32;%SystemDrive%\Windows;%SystemDrive%\Windows\System32;%PATH%

if not defined pausebuild (set pausebuild=0)
if not "%pausebuild%"=="0" if not "%pausebuild%"=="1" (set pausebuild=0)
if not defined usestartnetcmd (set usestartnetcmd=0)
if not "%usestartnetcmd%"=="0" if not "%usestartnetcmd%"=="1" (set usestartnetcmd=0)

(set reg32opt=)
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" (set reg32opt=/reg:32)

if "%ifwpath:~0,1%"==" " (set ifwpath=)
if "%ifwpath%"=="" for /f "usebackq tokens=5,*" %%G in (`reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Image for Windows (V2)_is1" %reg32opt% 2^> nul ^| find "Inno Setup: App Path"`) do set ifwpath=%%H
if "%ifwpath%"=="" if "%PROCESSOR_ARCHITECTURE%"=="AMD64" set ifwpath=%ProgramFiles(x86)%\TeraByte Unlimited\Image for Windows\V2
if "%ifwpath%"=="" set ifwpath=%ProgramFiles%\TeraByte Unlimited\Image for Windows\V2

if "%tbiviewpath:~0,1%"==" " (set tbiviewpath=)
if "%tbiviewpath%"=="" for /f "usebackq tokens=5,*" %%G in (`reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\TBIView_is1" %reg32opt% 2^> nul ^| find "Inno Setup: App Path"`) do set tbiviewpath=%%H
if "%tbiviewpath%"=="" if "%PROCESSOR_ARCHITECTURE%"=="AMD64" set tbiviewpath=%ProgramFiles(x86)%\TeraByte Unlimited\TBIView
if "%tbiviewpath%"=="" set tbiviewpath=%ProgramFiles%\TeraByte Unlimited\TBIView

if "%tbosdtpath:~0,1%"==" " (set tbosdtpath=)
if "%tbosdtpath%"=="" for /f "usebackq tokens=5,*" %%G in (`reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{F65A10A6-905E-497A-8D4F-2776802DF4C2}_is1" %reg32opt% 2^> nul ^| find "Inno Setup: App Path"`) do set tbosdtpath=%%H
if "%tbosdtpath%"=="" if "%PROCESSOR_ARCHITECTURE%"=="AMD64" set tbosdtpath=%ProgramFiles(x86)%\TeraByte Unlimited\TeraByte OSD Tool Suite Pro
if "%tbosdtpath%"=="" set tbosdtpath=%ProgramFiles%\TeraByte Unlimited\TeraByte OSD Tool Suite Pro

if "%inputlocale:~0,1%"==" " (set inputlocale=)

set /a winrebackupexists=0
if exist "WinRE_Backup\winre.wim" set /a winrebackupexists=1

set /a createbootfile=0

set /a usesavedsettings=0
for /f "usebackq tokens=* delims=" %%G in (`tbutil -iniread SavedSettings.ini -s Options -k UseSavedSettings -d 0`) do set usesavedsettings=%%G
if %usesavedsettings% NEQ 1 (set /a usesavedsettings=0)

if not defined screendpi (set /a screendpi=0)
if %screendpi% NEQ 192 if %screendpi% NEQ 144 if %screendpi% NEQ 120 if %screendpi% NEQ 96 (set /a screendpi=0)


:: --------------------
:: Check for Windows 7 or 8
tbutil -winver -q
set /a windowsversion=%errorlevel%
if %windowsversion% LEQ 8 goto :NoWin7
if %windowsversion% GEQ 15 goto :NoWin7


:: --------------------
:: Check tbutil version
tbutil -filever tbutil.exe -c 1.5 > nul
if %errorlevel% LSS 3 (
	echo.
	echo Error: Requires tbutil version 1.5 or later.
	echo.
	echo Script aborted.
	echo.
	tbutil -pause -m "Press any key to exit script..."
	goto :End
)


:: --------------------
:: Check Build Mode
if not defined buildmode (set /a buildmode=0)
if %buildmode% GTR 4 set /a buildmode=0
if %buildmode% EQU 4 (set /a createbootfile=1) & (set /a buildmode=2)
if %buildmode% GTR 0 goto :BuildModeSet


:: --------------------
:: Display Menu
tbutil -console -row
if %errorlevel% LSS 27 tbutil -console -row 27
:DisplayMenu
if %usesavedsettings% EQU 1 (set MSS_Status=Saved settings will be used for build) else if exist SavedSettings.ini (set MSS_Status=Saved settings will not be used for build) else (set MSS_Status=Saved settings not found)
cls
echo.
echo ==============================================================================
echo   TeraByte WinRE Builder                                           ver. %tbwinre_ver%
echo ==============================================================================
echo.
echo.
echo Please make a selection from the following choices:
echo.
echo   1 - Modify the Windows Recovery Environment (WinRE) accessed via F8 
echo       when booting (Windows 7) or the Boot/Restart menu (Windows 8)
echo.
echo   2 - Create a TBWinRE CD, USB Flash Drive (UFD), or ISO file
if %winrebackupexists% EQU 1 (
	echo.
	echo   3 - Restore the original winre.wim file. Use this option to return the 
	echo       Recovery Environment to its original state.
	echo.
	echo   4 - Create boot file TBWinRE.bin for use with TeraByte's BOOTFILE
	echo       program.
	echo.
	echo   5 - View online TBWinRE tutorial
	echo.
	echo   6 - Manage saved settings [%MSS_Status%]
	echo.
	echo   7 - Exit script
	echo.
	tbutil -choice -c 1234567 -e 1,2,3,7,8,9,10 -m "Press the number of your selection: "
) else (
	echo.
	echo   3 - Create boot file TBWinRE.bin for use with TeraByte's BOOTFILE
	echo       program.
	echo.
	echo   4 - View online TBWinRE tutorial
	echo.
	echo   5 - Manage saved settings [%MSS_Status%]
	echo.
	echo   6 - Exit script
	echo.
	tbutil -choice -c 123456 -e 1,2,7,8,9,10 -m "Press the number of your selection: "
)
if %errorlevel% EQU 10 goto :End
if %errorlevel% EQU 9 goto :ManageSettings
if %errorlevel% EQU 8 goto :ViewTutorial
set /a buildmode=%errorlevel%
if %buildmode% EQU 7 (set /a createbootfile=1) & (set /a buildmode=2)
if %buildmode% EQU 0 echo Error: Invalid build mode. & goto :End
if %buildmode% GTR 3 echo Error: Invalid build mode. & goto :End
:BuildModeSet
echo.
echo.


:: --------------------
:: Apply saved settings
if exist SavedSettings_Apply.cmd del SavedSettings_Apply.cmd > nul
if exist TBLauncher_Saved.ini del TBLauncher_Saved.ini > nul
if exist startnet_Saved.cmd del startnet_Saved.cmd > nul
tbutil -applysavedbuildsettings
if %errorlevel% EQU 0 if %usesavedsettings% EQU 1 (
	echo.
	echo Using saved settings...
	if exist SavedSettings_Apply.cmd (
		call SavedSettings_Apply.cmd
		del SavedSettings_Apply.cmd > nul
	)
)


:: --------------------
:: Check if DISM.EXE is available
if not exist "%SystemRoot%\System32\dism.exe" if not exist "%SystemDrive%\Windows\System32\dism.exe" goto :NoDISM


:: --------------------
:: Check if script has administrator privileges
dism.exe > nul
if %errorlevel% EQU 740 goto :NonAdmin


:: --------------------
:: Check if IFW is installed.
if not exist "%ifwpath%\imagew.exe" goto :NoIFW
if not exist "%ifwpath%\imagew64.exe" goto :NoIFW


:: --------------------
:: Check if TBOSDT is installed (required for bootfile)
if %createbootfile% EQU 1 (
	if not exist "!tbosdtpath!\win\tbosdtw.exe" goto :NoTBOSDT
	if not exist "!tbosdtpath!\win\tbosdtw64.exe" goto :NoTBOSDT
	if not exist "!tbosdtpath!\win\bootfile.exe" goto :NoTBOSDT
	if not exist "!tbosdtpath!\win\bootfile64.exe" goto :NoTBOSDT

	tbutil -filever "!tbosdtpath!\win\tbosdtw.exe" -c 1.47 > nul
	if !errorlevel! LSS 3 goto :NoTBOSDT
	tbutil -filever "!tbosdtpath!\win\tbosdtw64.exe" -c 1.47 > nul
	if !errorlevel! LSS 3 goto :NoTBOSDT
	tbutil -filever "!tbosdtpath!\win\bootfile.exe" -c 2.0.5 > nul
	if !errorlevel! LSS 3 goto :NoTBOSDT
	tbutil -filever "!tbosdtpath!\win\bootfile64.exe" -c 2.0.5 > nul
	if !errorlevel! LSS 3 goto :NoTBOSDT
)


:: --------------------
:: Check if imagew.ini is available
if %buildmode% EQU 3 goto :SkipImagewCheck
if not exist imagew.ini (
	echo ; This file contains the license key for Image for Windows.> imagew.ini
	echo ; Enter the key in the following format: Name Key>> imagew.ini
	echo ;>> imagew.ini
	echo ; If the key is missing or invalid, Image for Windows will run in trial mode.>> imagew.ini
	echo ;>> imagew.ini
	echo ; For example:>> imagew.ini
	echo ;>> imagew.ini
	echo ; [License]>> imagew.ini
	echo ; Key=John Smith 000000-111111-222222-333333-444444-555555-666666-777777-888888-999999>> imagew.ini
	echo ;>> imagew.ini
	echo [License]>> imagew.ini
	echo Key=>> imagew.ini
)
if not exist imagew.ini (
	echo.
	echo Unable to create imagew.ini file. Script aborted.
	echo.
	tbutil -pause -m "Press any key to exit script..."
	goto :End
)
:CheckImagewFile
tbutil -checkkey
if %errorlevel% EQU 3 goto :SkipImagewCheck
echo ----------------------------------------------------------------------------
echo --[ Product Key Notice ]----------------------------------------------------
echo ----------------------------------------------------------------------------
echo The imagew.ini file does not appear to contain a valid Product Key.
echo If the product key is not valid, Image for Windows will run in trial mode.
echo.
echo What would you like to do?
echo.
echo   1 - Apply product key to build (script will continue after Notepad exits)
echo.
echo   2 - Continue in trial mode
echo.
echo   3 - Exit script
echo.
tbutil -choice -c 123 -m "Press the number of your selection: "
if %errorlevel% EQU 3 goto :End
if %errorlevel% EQU 0 echo Error: Invalid selection. & goto :End
if %errorlevel% EQU 1 (
	notepad imagew.ini
	echo. & echo.
	goto :CheckImagewFile
)
:SkipImagewCheck


:: Skip locating WinRE.WIM if backup exists and creating CD/ISO/UFD
if %buildmode% EQU 2 if %winrebackupexists% EQU 1 (
	set WinRE_Path=!tbpath!\WinRE_Backup
	echo.
	echo WinRE image found.
	goto :skipBackupWinRE
)


:: --------------------
:: Locate WinRE.WIM file
echo.
echo Locating WinRE image...
(set WinRE_GUID=)
(set recseqdrv=)
(set recseqpath=)
(set WinRE_VolGUID=)
for /f "usebackq tokens=1,2 delims={} " %%G in (`bcdedit.exe /enum {current} ^| find "recoverysequence"`) do set WinRE_GUID=%%H
if "%WinRE_GUID%"=="" goto :RecSeqNotFound
for /f "usebackq tokens=1-4 delims=[]=, " %%G in (`bcdedit.exe /enum {%WinRE_GUID%} ^| find "device"`) do (
	set recseqdrv=%%I
	set recseqpath=%%~pJ
)
if "%recseqdrv%"=="" goto :RecSeqNotValid
if "%recseqpath%"=="" goto :RecSeqNotValid
if "%recseqdrv%"=="attached" goto :RecSeqNotValid
set recseqpath=%recseqpath:~0,-1%
echo WinRE Location:
echo.  [%recseqdrv%%recseqpath%]
if not "%recseqdrv:~1,6%"=="Device" goto :SetWinREPath
for /f "usebackq tokens=1 delims=" %%G in (`tbutil -volguid %recseqdrv%`) do set WinRE_VolGUID=%%G
set WinRE_VolGUID=%WinRE_VolGUID:~0,-1%
if not "%WinRE_VolGUID:~0,4%"=="\\?\" goto :VolGUIDError
set recseqdrv=%WinRE_VolGUID%


:SetWinREPath
set WinRE_Path=%recseqdrv%%recseqpath%
if exist "%WinRE_Path%\winre.wim" echo WinRE image found.
if not exist "%WinRE_Path%\winre.wim" goto :WinREWimNotFound
(set winreattr=)
(set winreattrstr=)
for /f "usebackq tokens=* delims=" %%G in (`attrib "%WinRE_Path%\winre.wim"`) do (set winreattr=%%G)
if "%winreattr:~3,1%"=="S" (set winreattrstr=+s)
if "%winreattr:~4,1%"=="H" (set winreattrstr=%winreattrstr% +h)
if "%winreattr:~5,1%"=="R" (set winreattrstr=%winreattrstr% +r)


:: --------------------
:: Restore WinRE.WIM file from backup
if %buildmode% NEQ 3 goto :skipRestoreWinRE
if not exist "WinRE_Backup\winre.wim" (
	echo.
	echo Backup copy of winre.wim not found. Restore aborted.
	echo.
	tbutil -pause -m "Press any key to exit script..."
	goto :End
)
echo.
echo Restoring winre.wim from backup...
attrib -s -h -r "%WinRE_Path%\winre.wim" > nul
del "%WinRE_Path%\winre.wim" > nul
copy "WinRE_Backup\winre.wim" "%WinRE_Path%\winre.wim" > nul
fc /b "WinRE_Backup\winre.wim" "%WinRE_Path%\winre.wim" > nul
if errorlevel 1 (
	echo Restore failed.
	echo.
	tbutil -pause -m "Press any key to exit script..."
	goto :End
)
attrib %winreattrstr% "%WinRE_Path%\winre.wim" > nul
if not exist "%WinRE_Path%\ReCustomization.xml" goto :skipResetWin8Cust
(set Win8RECust=)
for /f "usebackq tokens=* delims=" %%G in (`findstr /i /c:"Image for Windows" "%WinRE_Path%\ReCustomization.xml"`) do set Win8RECust=%%G
if "%Win8RECust%"=="" goto :skipResetWin8Cust
echo Removing Windows 8 WinRE customization...
attrib -s -h "%WinRE_Path%\ReCustomization.xml"
del "%WinRE_Path%\ReCustomization.xml" > nul
if exist "%SystemRoot%\System32\Recovery\ReCustomization.xml" (
	attrib -s -h "%SystemRoot%\System32\Recovery\ReCustomization.xml"
	del "%SystemRoot%\System32\Recovery\ReCustomization.xml" > nul
)
:skipResetWin8Cust
echo Restore complete.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End
:skipRestoreWinRE


:: --------------------
:: Back up WinRE.WIM file
if exist "WinRE_Backup\winre.wim" goto :skipBackupWinRE
echo.
echo Saving backup of winre.wim file...
attrib -s -h "%WinRE_Path%\winre.wim"
if not exist "WinRE_Backup" md "WinRE_Backup"
copy "%WinRE_Path%\winre.wim" "WinRE_Backup" > nul
fc /b "WinRE_Backup\winre.wim" "%WinRE_Path%\winre.wim" > nul
if errorlevel 1 (
	echo Backup failed. Script aborted.
	if exist "WinRE_Backup\winre.wim" del "WinRE_Backup\winre.wim"
	echo.
	tbutil -pause -m "Press any key to exit script..."
	goto :End
)
attrib +s +h "%WinRE_Path%\winre.wim"
echo Backup created successfully.
:skipBackupWinRE


:: --------------------
:: Determine WIM file x86 or x64
(set tbx64=)
(set WinREArch=)
for /f "usebackq tokens=* delims=" %%G in (`dism /get-wiminfo /wimfile:"%WinRE_Path%\winre.wim" /index:1 ^| find "(x64)"`) do (set WinREArch=x64)
if "%WinREArch%"=="" for /f "usebackq tokens=* delims=" %%G in (`dism /get-wiminfo /wimfile:"%WinRE_Path%\winre.wim" /index:1 ^| find ": x64"`) do (set WinREArch=x64)
if "%WinREArch%"=="" for /f "usebackq tokens=* delims=" %%G in (`dism /get-wiminfo /wimfile:"%WinRE_Path%\winre.wim" /index:1 ^| find "(x86)"`) do (set WinREArch=x86)
if "%WinREArch%"=="" for /f "usebackq tokens=* delims=" %%G in (`dism /get-wiminfo /wimfile:"%WinRE_Path%\winre.wim" /index:1 ^| find ": x86"`) do (set WinREArch=x86)
if "%WinREArch%"=="x64" (set tbx64=64)
if "%tbx64%"=="" if not "%WinREArch%"=="x86" (set WinREArch=Unknown)
echo.
echo WinRE.WIM file architecture: (%WinREArch%)
if "%WinREArch%"=="Unknown" echo WARNING: WinRE.WIM architecture not set or unknown.


:: --------------------
:: Copy WinRE.WIM for processing
echo.
echo Copying WinRE image...
if not exist "build" md "build"
copy "WinRE_Backup\winre.wim" "build" > nul


:: --------------------
:: Mount the WinRE image for processing
(set foldermounted=)
for /f "usebackq tokens=1,2,3 delims=:" %%G in (`dism /get-mountedwiminfo ^| find /i "!tbpath!\mount"`) do set foldermounted=%%I
if not "%foldermounted%"=="" (
	echo. & echo WARNING: Mount folder in use. Attempting cleanup...
	Dism /unmount-Wim /MountDir:"mount" /discard
	rd /s /q "mount" > nul
	Dism /cleanup-wim > nul
)
echo.
echo Mounting WinRE image...
if exist "mount" rd /s /q "mount" > nul
if not exist "mount" md "mount"
Dism /Mount-Wim /WimFile:"%tbpath%\build\winre.wim" /index:1 /MountDir:"%tbpath%\mount"
if %errorlevel% EQU 0 goto :skipMountError
echo.
echo --------------------------------------------------------------------------
echo --[ Mount Error ]---------------------------------------------------------
echo --------------------------------------------------------------------------
echo The WinRE image couldn't be mounted successfully. Please make sure
echo no programs (e.g. Explorer) are currently accessing the mount folder 
echo and that the mount folder is empty. Then press a key to attempt 
echo another mount.
echo.
echo Mount folder: %tbpath%\mount
echo --------------------------------------------------------------------------
echo.
tbutil -pause -m "Press any key to try the mount again..."
echo.
echo Mounting WinRE image (2nd attempt)...
if exist "mount" rd /s /q "mount" > nul
Dism /cleanup-wim
if not exist "mount" md "mount"
Dism /Mount-Wim /WimFile:"%tbpath%\build\winre.wim" /index:1 /MountDir:"%tbpath%\mount"
if %errorlevel% NEQ 0 goto :DISMMountError
:skipMountError


:: --------------------
:: Check architecture (if necessary)
if "%WinREArch%"=="Unknown" (
	if exist "mount\Windows\SysWOW64" (set tbx64=64) & (set WinREArch=x64)
	if not exist "mount\Windows\SysWOW64" (set tbx64=) & (set WinREArch=x86)
	echo.
	echo WinRE.WIM file architecture: ^(!WinREArch!^)
)


:: ---------------------
:: Set Input Locale
:: ---------------------
if not "%inputlocale%"=="" (
	echo.
	echo Setting input locale %inputlocale%...
	dism /set-inputlocale:%inputlocale% /image:"!tbpath!\mount"
)


:: ---------------------
:: Modify WIM startup
:: ---------------------
if exist "mount\setup.exe" (
	ren "mount\setup.exe" setup_tb_.exe > nul
	attrib +h "mount\setup_tb_.exe" > nul
)
attrib -r "mount\Windows\System32\winpeshl.ini" > nul
if exist "mount\Windows\System32\winpeshl.ini" del "mount\Windows\System32\winpeshl.ini" > nul
if exist "mount\Windows\System32\setup.bmp" del "mount\Windows\System32\setup.bmp" > nul
echo [LaunchApps] > "mount\Windows\System32\winpeshl.ini"
tbutil -filever "mount\Windows\System32\winpeshl.exe" -c 6.3 > nul
(set FileVer_winpeshl=%errorlevel%)
if %FileVer_winpeshl% GEQ 3 (
	if %createbootfile% EQU 1 echo %%SystemDrive%%\Windows\System32\bootfile.exe, /restore /noui /notifyos >> "mount\Windows\System32\winpeshl.ini"
	echo %%SystemDrive%%\Windows\System32\chgres.exe, !screenresolution! >> "mount\Windows\System32\winpeshl.ini"
)
if %FileVer_winpeshl% LEQ 2 (
	if %createbootfile% EQU 1 echo %%SystemDrive%%\Windows\System32\bootfile.exe, "/restore /noui /notifyos" >> "mount\Windows\System32\winpeshl.ini"
	echo %%SystemDrive%%\Windows\System32\chgres.exe, "!screenresolution!" >> "mount\Windows\System32\winpeshl.ini"
)
echo %%SystemDrive%%\Windows\System32\tblauncher.exe >> "mount\Windows\System32\winpeshl.ini"
if %usestartnetcmd% EQU 1 del "mount\Windows\System32\winpeshl.ini"
reg load HKLM\TBWINPE_SYSTEM "mount\windows\system32\config\system" > nul
reg add "HKLM\TBWINPE_SYSTEM\ControlSet001\Control\Session Manager\Environment" /v TBWinPE /t REG_SZ /d "1" /f > nul
if not exist "mount\Windows\System32\config\systemprofile\Desktop" md "mount\Windows\System32\config\systemprofile\Desktop"
reg load HKLM\TBWINPE_SOFTWARE "mount\windows\system32\config\software" > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\CLSID\{AE054212-3535-4430-83ED-D501AA6680E6}" /ve /t REG_SZ /d "Shell Name Space ListView" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\CLSID\{AE054212-3535-4430-83ED-D501AA6680E6}\InProcserver32" /ve /t REG_EXPAND_SZ /d "%%SystemRoot%%\System32\explorerframe.dll" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\CLSID\{AE054212-3535-4430-83ED-D501AA6680E6}\InProcserver32" /v ThreadingModel /t REG_SZ /d "Apartment" /f > nul
reg load HKLM\TBWINPE_DEFAULT "mount\windows\system32\config\default" > nul
reg add "HKLM\TBWINPE_DEFAULT\Control Panel\Desktop" /t REG_SZ /v "WallpaperStyle" /d "2" /f > nul
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" (
	if "%tbx64%"=="64" copy "%SystemRoot%\System32\explorerframe.dll" "mount\Windows\System32" > nul
	if "%tbx64%"=="" copy "%SystemRoot%\SysWOW64\explorerframe.dll" "mount\Windows\System32" > nul
)
if "%PROCESSOR_ARCHITECTURE%"=="x86" (
	if "%tbx64%"=="" copy "%SystemRoot%\System32\explorerframe.dll" "mount\Windows\System32" > nul
)
tbutil -configurewinpe
if %errorlevel% NEQ 1 echo WARNING: Error configuring WinPE!


:: ---------------------
:: Add TBLauncher
:: ---------------------
echo.
echo Adding TBLauncher...
copy "tblauncher%tbx64%.exe" "mount\Windows\system32\TBLauncher.exe" > nul
copy "tblauncher.ini" "mount\Windows\system32" > nul
if exist "mount\Windows\system32\InitScript.cmd" del "mount\Windows\system32\InitScript.cmd" > nul
if exist "mount\Windows\system32\RunScript.cmd" del "mount\Windows\system32\RunScript.cmd" > nul
if exist InitScript.cmd copy InitScript.cmd "mount\Windows\system32" > nul
if exist RunScript.cmd copy RunScript.cmd "mount\Windows\system32" > nul
if %usesavedsettings% EQU 1 if exist TBLauncher_Saved.ini (
	copy TBLauncher_Saved.ini "mount\Windows\system32\TBLauncher.ini" > nul
	del TBLauncher_Saved.ini > nul
)


:: ---------------------
:: Add IFW
:: ---------------------
echo.
echo Adding Image for Windows...
if not exist "mount\Program Files\TeraByte Unlimited\Image for Windows\V2" md "mount\Program Files\TeraByte Unlimited\Image for Windows\V2"
copy "%ifwpath%\imagew%tbx64%.exe" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2\imagew.exe" > nul
if "%tbx64%"=="64" copy "%ifwpath%\imagew64.exe" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2" > nul
copy "%ifwpath%\cdboot.f35" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2" > nul
copy "%ifwpath%\cdboot.ifd" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2" > nul
copy "%ifwpath%\ifw.ini" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2" > nul
copy "ifw.ini" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2" > nul
copy "%ifwpath%\ifwlang.dll" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2" > nul
copy "%ifwpath%\partinfg%tbx64%.exe" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2\partinfg.exe" > nul
if exist "%ifwpath%\cdboot.ifl" (
	copy "%ifwpath%\cdboot.ifl" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2" > nul
	xcopy /e /y /r /i "%ifwpath%\cdboot" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2\cdboot" > nul
)
if exist "imagew.ini" (
	if exist "mount\Program Files\TeraByte Unlimited\Image for Windows\V2\imagew.ini" attrib -r "mount\Program Files\TeraByte Unlimited\Image for Windows\V2\imagew.ini" > nul
	copy "imagew.ini" "mount\Program Files\TeraByte Unlimited\Image for Windows\V2" > nul
	attrib +r "mount\Program Files\TeraByte Unlimited\Image for Windows\V2\imagew.ini" > nul
)
reg add "HKLM\TBWINPE_SOFTWARE\Classes\TBIFile" /ve /t REG_SZ /d "TeraByte Image File" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\TBIFile\DefaultIcon" /ve /t REG_SZ /d "X:\Program Files\TeraByte Unlimited\Image for Windows\V2\imagew.exe,0" /f > nul
:: Create imagew.cmd
echo @echo off > "mount\Windows\System32\imagew.cmd"
echo start "IFW" "%%SystemDrive%%\Program Files\TeraByte Unlimited\Image for Windows\V2\imagew.exe" >> "mount\Windows\System32\imagew.cmd"


:: ---------------------
:: Add TBIView
:: ---------------------
if not exist "%tbiviewpath%\tbiview%tbx64%.exe" goto :skipTBIView
echo.
echo Adding TBIView...
if not exist "mount\Program Files\TeraByte Unlimited\TBIView" md "mount\Program Files\TeraByte Unlimited\TBIView"
copy "%tbiviewpath%\tbiview%tbx64%.exe" "mount\Program Files\TeraByte Unlimited\TBIView\tbiview.exe" > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\.tbi" /ve /t REG_SZ /d "TBIViewFile" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\TBIViewFile" /ve /t REG_SZ /d "TeraByte Image File" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\TBIViewFile\DefaultIcon" /ve /t REG_SZ /d "X:\Program Files\TeraByte Unlimited\TBIView\tbiview.exe,0" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\TBIViewFile\shell\open" /v Icon /t REG_SZ /d "X:\Program Files\TeraByte Unlimited\TBIView\tbiview.exe,0" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\TBIViewFile\shell\open\command" /ve /t REG_SZ /d "\"X:\Program Files\TeraByte Unlimited\TBIView\tbiview.exe\" \"%%1\"" /f > nul
:: Create tbiview.cmd
echo @echo off > "mount\Windows\System32\tbiview.cmd"
echo start "TBIView" "%%SystemDrive%%\Program Files\TeraByte Unlimited\TBIView\tbiview.exe" >> "mount\Windows\System32\tbiview.cmd"
:: ---------------------
:skipTBIView


:: ---------------------
:: Add TBIMount
:: ---------------------
if not exist "%tbiviewpath%\tbimount%tbx64%.exe" goto :skipTBIMount
echo.
echo Adding TBIMount...
if not exist "mount\Program Files\TeraByte Unlimited\TBIView" md "mount\Program Files\TeraByte Unlimited\TBIView"
if "%tbx64%"=="64" copy "%tbiviewpath%\tbimount.x64.sys" "mount\Windows\System32\Drivers\tbimount.sys" > nul
if "%tbx64%"=="" copy "%tbiviewpath%\tbimount.xp.sys" "mount\Windows\System32\Drivers\tbimount.sys" > nul
copy "%tbiviewpath%\tbimount%tbx64%.exe" "mount\Program Files\TeraByte Unlimited\TBIView\tbimount.exe" > nul
reg add HKLM\TBWINPE_SYSTEM\ControlSet001\Services\TBIMount /f > nul
reg add HKLM\TBWINPE_SYSTEM\ControlSet001\Services\TBIMount /v Type /t REG_DWORD /d 1 /f > nul
reg add HKLM\TBWINPE_SYSTEM\ControlSet001\Services\TBIMount /v Start /t REG_DWORD /d 3 /f > nul
reg add HKLM\TBWINPE_SYSTEM\ControlSet001\Services\TBIMount /v ErrorControl /t REG_DWORD /d 1 /f > nul
reg add HKLM\TBWINPE_SYSTEM\ControlSet001\Services\TBIMount /v DisplayName /t REG_SZ /d TBIMount /f > nul
reg add HKLM\TBWINPE_SYSTEM\ControlSet001\Services\TBIMount /v ImagePath /t REG_SZ /d "system32\drivers\tbimount.sys" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\TBIViewFile\shell\Mount as Drive Letter" /v Icon /t REG_SZ /d "X:\Program Files\TeraByte Unlimited\TBIView\tbimount.exe,0" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\TBIViewFile\shell\Mount as Drive Letter\command" /ve /t REG_SZ /d "\"X:\Program Files\TeraByte Unlimited\TBIView\tbimount.exe\" mount * \"%%1\"" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\Drive\shell\TBIMount - Unmount Drive Letter" /v Icon /t REG_SZ /d "X:\Program Files\TeraByte Unlimited\TBIView\tbimount.exe,0" /f > nul
reg add "HKLM\TBWINPE_SOFTWARE\Classes\Drive\shell\TBIMount - Unmount Drive Letter\command" /ve /t REG_SZ /d "\"X:\Program Files\TeraByte Unlimited\TBIView\tbimount.exe\" unmount %%1" /f > nul
:: Create tbimount.cmd
echo @echo off > "mount\Windows\System32\tbimount.cmd"
echo start "TBIMount" "%%SystemDrive%%\Program Files\TeraByte Unlimited\TBIView\tbimount.exe" >> "mount\Windows\System32\tbimount.cmd"
:: ---------------------
:skipTBIMount


:: ---------------------
:: Add TBOSDT
:: ---------------------
if not exist "%tbosdtpath%\win\tbosdtw%tbx64%.exe" goto :skipTBOSDT
echo.
echo Adding TeraByte OSD Tool Suite Pro (TBOSDT)...
if not exist "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\win" md "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\win"
if not exist "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\scripts" md "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\scripts"
if not exist "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\scripts\public" md "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\scripts\public"
copy "%tbosdtpath%\win\*.*" "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\win" > nul
copy "%tbosdtpath%\scripts\*.*" "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\scripts" > nul
if exist "%tbosdtpath%\scripts\public" xcopy /e /y /r "%tbosdtpath%\scripts\public\*.*" "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\scripts\public" > nul
:: Copy IFW & TBOSDT into x86 folder, if x64 (default location for some tbs scripts)
if "%tbx64%"=="64" (
	if not exist "mount\Program Files (x86)\TeraByte Unlimited\Image for Windows\V2" md "mount\Program Files (x86)\TeraByte Unlimited\Image for Windows\V2"
	xcopy /e /y /r /i "mount\Program Files\TeraByte Unlimited\Image for Windows\V2" "mount\Program Files (x86)\TeraByte Unlimited\Image for Windows\V2" > nul
	attrib +r "mount\Program Files (x86)\TeraByte Unlimited\Image for Windows\V2\imagew.ini" > nul
	xcopy /e /y /r /i "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\*.*" "mount\Program Files (x86)\TeraByte Unlimited\TeraByte OSD Tool Suite Pro" > nul
)
copy "mount\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\win\bootfile%tbx64%.exe" "mount\Windows\System32\bootfile.exe" > nul
:: Create tbosdtw.cmd
echo @echo off > "mount\Windows\System32\tbosdtw.cmd"
echo start "TBOSDT" "%%SystemDrive%%\Program Files\TeraByte Unlimited\TeraByte OSD Tool Suite Pro\win\tbosdtw%tbx64%.exe" >> "mount\Windows\System32\tbosdtw.cmd"
:skipTBOSDT


:: --------------------
:: Modify WinRE files, resolution files, background, etc.
echo.
echo Finalizing WinRE build...
reg unload HKLM\TBWINPE_SYSTEM > nul
reg unload HKLM\TBWINPE_SOFTWARE > nul
reg unload HKLM\TBWINPE_DEFAULT > nul
copy "%systemroot%\system32\choice.exe" "mount\windows\system32" > nul
copy "%tbpath%\startnet.cmd" "mount\Windows\System32" > nul
if %usesavedsettings% EQU 1 if exist startnet_Saved.cmd (
	copy startnet_Saved.cmd "mount\Windows\system32\startnet.cmd" > nul
	del startnet_Saved.cmd > nul
)
if %createbootfile% EQU 1 (
	echo set textline "mount\Windows\System32\startnet.cmd" "bootfile /restore /noui /notifyos" /a "@echo off*" > tmpscript.run
	"!tbosdtpath!\win\tbosdtw.exe" tmpscript.run
	del tmpscript.run > nul
)
copy "%tbpath%\chgres%tbx64%.exe" "mount\Windows\System32\chgres.exe" > nul
echo Created using TBWinRE script version %tbwinre_ver%. > "mount\Windows\System32\TBWinRE.txt"

:: Build source
(set BuildSourceName=Unknown)
if exist "mount\Windows\System32\winpeshl.exe_ver.6.3" (set BuildSourceName=Windows 8.1 WinRE)
if exist "mount\Windows\System32\winpeshl.exe_ver.6.2" (set BuildSourceName=Windows 8.0 WinRE)
if exist "mount\Windows\System32\winpeshl.exe_ver.6.1" (set BuildSourceName=Windows 7 WinRE)
del "mount\Windows\System32\winpeshl.exe_ver.*" > nul 2>&1
if "%tbx64%"=="64" (set BuildSourceName=%BuildSourceName% [AMD64]) else (set BuildSourceName=%BuildSourceName% [x86])
echo Build source: %BuildSourceName% >> "mount\Windows\System32\TBWinRE.txt"

:: Set background image
copy "winpe.bmp" "mount\Windows\System32" > nul
copy "winpe.jpg" "mount\Windows\System32" > nul
if exist "mount\Windows\System32\winre.jpg" (
	takeown /f "mount\Windows\System32\winre.jpg" > nul
	icacls "mount\Windows\System32\winre.jpg" /grant *S-1-5-32-544:F > nul
	del "mount\Windows\System32\winre.jpg"
	copy "winpe.jpg" "%tbpath%\mount\Windows\System32\winre.jpg" > nul
)

:: Create shutdown.cmd
echo @echo off > "mount\Windows\System32\shutdown.cmd"
echo wpeutil shutdown >> "mount\Windows\System32\shutdown.cmd"

:: Add Drivers
if exist "Drivers" (
	echo.
	echo Adding drivers...
	Dism /image:"!tbpath!\mount" /Add-Driver /driver:"!tbpath!\Drivers" /recurse
)

:: Add Windows 8 WinRE customization
if %buildmode% NEQ 1 goto :NoWin8Cust
if %windowsversion% LEQ 10 goto :NoWin8Cust
if %windowsversion% GEQ 15 goto :NoWin8Cust
if exist "%WinRE_Path%\ReCustomization.xml" (
	(set Win8RECust=)
	for /f "usebackq tokens=* delims=" %%G in (`findstr /i /c:"Image for Windows" "%WinRE_Path%\ReCustomization.xml"`) do set Win8RECust=%%G
	if "!Win8RECust!"=="" goto :NoWin8Cust
)
echo.
echo Applying Windows 8 WinRE customization...
reagentc /setbootshelllink /configfile "Win8_ReCustomization.xml" > nul
echo.>> "mount\Windows\system32\tblauncher.ini"
echo [ForceOptions]>> "mount\Windows\system32\tblauncher.ini"
echo Mode=WinRE>> "mount\Windows\system32\tblauncher.ini"
:NoWin8Cust

:: Copy OSK files
copy "%SystemRoot%\System32\osk.exe" "mount\Windows\System32" > nul
copy "%SystemRoot%\System32\osksupport.dll" "mount\Windows\System32" > nul

:: Copy CD/ISO booting files
copy "mount\Windows\Boot\DVD\PCAT\etfsboot.com" > nul
if not exist "etfsboot.com" copy "%SystemRoot%\Boot\DVD\PCAT\etfsboot.com" > nul
copy "mount\Windows\Boot\DVD\EFI\en-US\efisys_noprompt.bin" "efisys.bin" > nul
if not exist "efisys.bin" copy "mount\Windows\Boot\DVD\EFI\en-US\efisys.bin" > nul
if not exist "efisys.bin" copy "%SystemRoot%\Boot\DVD\EFI\en-US\efisys_noprompt.bin" "efisys.bin" > nul
if not exist "efisys.bin" copy "%SystemRoot%\Boot\DVD\EFI\en-US\efisys.bin" > nul

:: This pause allows the advanced user to verify the contents of the mount folder
:: and to add additional files/folders.
if %pausebuild% EQU 1 (
	echo. & echo.
	echo --------------------------------------------------------------------------
	echo --[ Build Paused ]--------------------------------------------------------
	echo --------------------------------------------------------------------------
	echo The build has been paused to allow the mounted image to be checked or
	echo modified. Just press a key if unsure what to do.
	echo --------------------------------------------------------------------------
	echo.
	tbutil -pause -m "Press any key to continue with the build..."
	echo.
)


:: --------------------
:: Save & Unmount WinRE image
echo.
echo Saving WinRE image...
set /a dismsaveerror=0
Dism /commit-Wim /MountDir:"%tbpath%\mount"
if not %errorlevel% EQU 0 set /a dismsaveerror=1
echo.
echo Unmounting WinRE image (this may take several minutes)...
Dism /unmount-Wim /MountDir:"%tbpath%\mount" /discard
if %errorlevel% EQU 0 goto :skipUnmountError
echo.
echo --------------------------------------------------------------------------
echo --[ Unmount Error ]-------------------------------------------------------
echo --------------------------------------------------------------------------
echo The WinRE image couldn't be unmounted successfully. Please make sure
echo no programs (e.g. Explorer) are currently accessing the mount folder 
echo or its contents and then press a key to attempt another unmount.
echo.
echo Mount folder: %tbpath%\mount
echo --------------------------------------------------------------------------
echo.
tbutil -pause -m "Press any key to try the unmount again..."
echo.
echo Unmounting WinRE image (2nd attempt)...
Dism /unmount-Wim /MountDir:"%tbpath%\mount" /discard
if %errorlevel% EQU 0 goto :skipUnmountError
:: Delete mount folder and attempt cleanup
echo.
echo Attempting to remove mount folder...
if exist "mount" rd /s /q "mount" > nul
echo Attempting WIM cleanup...
Dism /cleanup-wim
:skipUnmountError
if %dismsaveerror% EQU 1 goto :DISMSaveError


:: --------------------
:: Finalize build
echo.
if %buildmode% EQU 1 goto :CreateWinRE
if %buildmode% EQU 2 goto :CreateBootMedia

:CreateWinRE
echo Updating WinRE image...
attrib -s -h -r "%WinRE_Path%\winre.wim" > nul
del "%WinRE_Path%\winre.wim" > nul
copy "build\winre.wim" "%WinRE_Path%\winre.wim" > nul
attrib %winreattrstr% "%WinRE_Path%\winre.wim" > nul
goto :BuildFinished

:CreateBootMedia
echo Creating CD/UFD/ISO file layout...
:: Create folders
if not exist "ISO" md "ISO"
if not exist "ISO\Boot" md "ISO\boot"
if not exist "ISO\Boot\FONTS" md "ISO\boot\FONTS"
if not exist "ISO\Sources" md "ISO\sources"
if exist "%SystemRoot%\Boot\Resources\bootres.dll" (
	if not exist "ISO\Boot\Resources" md "ISO\Boot\Resources"
	copy "%SystemRoot%\Boot\Resources\bootres.dll" "ISO\Boot\Resources" > nul
)
if not exist "ISO\TBData" md "ISO\TBData"
echo Created using TBWinRE script version %tbwinre_ver%. > "ISO\TBData\TBWinRE.txt"
echo Build source: %BuildSourceName% >> "ISO\TBData\TBWinRE.txt"
:: Copy booting files
copy "%SystemRoot%\Boot\DVD\PCAT\BCD" "ISO\Boot" > nul
copy "%SystemRoot%\Boot\DVD\PCAT\BOOT.SDI" "ISO\Boot" > nul
copy "%SystemRoot%\Boot\PCAT\bootmgr" "ISO" > nul
copy "%SystemRoot%\Boot\Fonts\*.*" "ISO\Boot\FONTS" > nul

if %windowsversion% EQU 9 (
	if not exist "ISO\Boot\BCD" copy "C:\Windows\winsxs\amd64_microsoft-windows-b..nvironment-dvd-pcat_31bf3856ad364e35_6.1.7600.16385_none_f60cc30a4a2fb068\BCD" "ISO\Boot" > nul
	if not exist "ISO\Boot\boot.sdi" copy "C:\Windows\winsxs\amd64_microsoft-windows-b..nvironment-dvd-pcat_31bf3856ad364e35_6.1.7600.16385_none_f60cc30a4a2fb068\boot.sdi" "ISO\Boot" > nul
	if not exist "etfsboot.com" copy "C:\Windows\winsxs\x86_microsoft-windows-b..onment-dvd-etfsboot_31bf3856ad364e35_6.1.7600.16385_none_82523ed4cbbd035a\etfsboot.com" "%tbpath%" > nul
)

set /a missingbootfiles=0
set /a missingCDbootfiles=0
if not exist "ISO\Boot\BCD" set /a missingbootfiles=1
if not exist "ISO\Boot\boot.sdi" set /a missingbootfiles=1
if not exist "etfsboot.com" set /a missingCDbootfiles=1
if not exist "ISO\bootmgr" set /a missingbootfiles=1

:: Copy EFI booting files
if not exist "%SystemRoot%\Boot\EFI\bootmgr.efi" goto :skipEFIfiles
if not exist "ISO\efi" md "ISO\efi"
if not exist "ISO\efi\boot" md "ISO\efi\boot"
if not exist "ISO\efi\microsoft" md "ISO\efi\microsoft"
if not exist "ISO\efi\microsoft\boot" md "ISO\efi\microsoft\boot"
if not exist "ISO\efi\microsoft\boot\fonts" md "ISO\efi\microsoft\boot\fonts"

copy "%SystemRoot%\Boot\EFI\bootmgr.efi" "ISO" > nul
copy "%SystemRoot%\Boot\EFI\bootmgfw.efi" "ISO\efi\boot\bootx64.efi" > nul
if "%PROCESSOR_ARCHITECTURE%"=="x86" if "%tbx64%"=="" ren "ISO\efi\boot\bootx64.efi" bootia32.efi > nul
copy "%SystemRoot%\Boot\DVD\EFI\BCD" "ISO\efi\microsoft\boot" > nul
copy "%SystemRoot%\Boot\Fonts\*.*" "ISO\efi\microsoft\boot\fonts" > nul

if %windowsversion% EQU 9 (
	if not exist "efisys.bin" copy "C:\Windows\winsxs\amd64_microsoft-windows-b..ironment-dvd-efisys_31bf3856ad364e35_6.1.7601.17514_none_c0c6eceaf97c4827\efisys.bin" "%tbpath%" > nul
	if not exist "ISO\efi\microsoft\boot\BCD" copy "C:\Windows\winsxs\amd64_microsoft-windows-b..environment-dvd-efi_31bf3856ad364e35_6.1.7600.16385_none_313c88fc9e3423aa\BCD" "ISO\efi\microsoft\boot" > nul
)

if not exist "efisys.bin" set /a missingbootfiles=1
if not exist "ISO\efi\microsoft\boot\BCD" set /a missingbootfiles=1
if not exist "ISO\bootmgr.efi" set /a missingbootfiles=1
if not exist "ISO\efi\boot\boot*.efi" set /a missingbootfiles=1

if exist "%SystemRoot%\Boot\Resources\bootres.dll" (
	if not exist "ISO\efi\microsoft\boot\resources" md "ISO\efi\microsoft\boot\resources" 
	copy "%SystemRoot%\Boot\Resources\bootres.dll" "ISO\efi\microsoft\boot\resources" > nul
)
:skipEFIfiles
if %missingbootfiles% EQU 1 (
	echo.
	echo --------------------------------------------------------------------------
	echo --[ Warning ]-------------------------------------------------------------
	echo --------------------------------------------------------------------------
	echo One or more of the boot files are missing. Media may not boot correctly.
	echo --------------------------------------------------------------------------
	echo.
	tbutil -pause -m "Press any key to continue..."
	echo.
)
if %missingbootfiles% EQU 0 if %missingCDbootfiles% EQU 1 (
	echo.
	echo --------------------------------------------------------------------------
	echo --[ Note ]----------------------------------------------------------------
	echo --------------------------------------------------------------------------
	echo A file necessary to create a bootable CD is missing. You will not be able
	echo to create a CD, DVD, or ISO file using MAKEDISK.
	echo --------------------------------------------------------------------------
	echo.
)
:: Copy WIM
copy "build\winre.wim" "ISO\Sources\boot.wim" > nul

:: Create TBWinRE.bin boot file
if %createbootfile% NEQ 1 goto :skipCreateBootFile
echo.
echo Creating boot file TBWinRE.bin...
(set bootfilesize=280)
tbutil -dirsize iso -s -q
if %errorlevel% GTR 0 (set /a bootfilesize=%errorlevel%+30)
echo del tbwinre.bin /y > tmpscript.run
echo add virtdrv TBWinRE.bin %bootfilesize% TBWinRE /b /fat32 /bs=vistabs.f32 >> tmpscript.run
echo open fs 0: tbwinre.bin >> tmpscript.run
echo copy file iso\*.* 0: /s /y >> tmpscript.run
echo close 0: >> tmpscript.run
"%tbosdtpath%\win\tbosdtw.exe" tmpscript.run > nul
del tmpscript.run > nul
echo :: This script will boot the TBWinRE.bin boot file. If the file has been > "Boot TBWinRE Boot File.cmd"
echo :: moved to a different path you will need to edit the path below. >> "Boot TBWinRE Boot File.cmd"
echo.  >> "Boot TBWinRE Boot File.cmd"
echo @echo off >> "Boot TBWinRE Boot File.cmd"
echo "%tbosdtpath%\win\bootfile%tbx64%.exe" "%tbpath%\TBWinRE.bin" >> "Boot TBWinRE Boot File.cmd"
echo Boot file created.
echo.
echo Run the "Boot TBWinRE Boot File.cmd" script to boot the system to the boot
echo file.
goto :BuildFinished
:skipCreateBootFile

:: Run MakeDisk
echo.
echo Press a key to launch TeraByte's MAKEDISK utility to create the TBWinRE
if %missingCDbootfiles% EQU 0 echo CD, USB flash drive (UFD), or ISO file boot media.
if %missingCDbootfiles% EQU 1 echo USB flash drive (UFD) boot media.
echo.
tbutil -pause
echo.
echo Launching MAKEDISK...
start "" makedisk.exe
goto :BuildFinished


:BuildFinished
rd /s /q "build" > nul
echo.
echo ==============================================================================
echo.
echo WinRE build process has finished.
echo.
echo ==============================================================================
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End



:: ---------------------------------------------------------------------

:: Incorrect Windows version
:NoWin7
echo.
echo This script requires Windows 7 or Windows 8.
echo.
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End


:: No IFW (imagew.exe/imagew64.exe) found
:NoIFW
echo.
echo Error: Can't find Image for Windows
echo.
echo Files imagew.exe and imagew64.exe not found in
echo %ifwpath%
echo.
echo Make sure Image for Windows 2.71 or later is installed and that the correct 
echo path is specified for Image for Windows in the script.
echo.
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End


:: No TBOSDT (tbosdtw.exe/bootfile.exe) found
:NoTBOSDT
echo.
echo Error: Can't find the TeraByte OS Deployment Tool Suite installation or
echo incorrect version installed.
echo.
echo Correct versions of tbosdtw.exe and bootfile.exe not found in
echo %tbosdtpath%\win
echo.
echo Make sure that the TeraByte OS Deployment Tool Suite version 1.47 or later is 
echo installed and that the correct path is specified in the script.
echo.
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End


:: No DISM.EXE found
:NoDISM
echo.
echo Error: Can't find DISM.EXE.
echo File dism.exe not found in %SystemRoot%\System32.
echo.
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End

:: Needs Administrator Privileges
:NonAdmin
echo.
echo TBWinRE.CMD requires administrator privileges to run. 
echo Please restart the script with the correct privileges.
echo.
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End

:RecSeqNotFound
echo.
echo A "recoverysequence" GUID for the currently booted Windows was not found.
echo WinRE appears to be disabled or not properly configured.
echo.
call :SearchForWinRE
if %buildmode% EQU 2 if exist "WinRE_Backup\winre.wim" goto :skipBackupWinRE
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End

:RecSeqNotValid
echo.
echo The "recoverysequence" GUID for the currently booted Windows was found, but
echo appears to be invalid or not properly configured.
echo.
call :SearchForWinRE
if %buildmode% EQU 2 if exist "WinRE_Backup\winre.wim" goto :skipBackupWinRE
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End

:VolGUIDError
echo.
echo Error obtaining volume GUID for WinRE partition.
echo.
call :SearchForWinRE
if %buildmode% EQU 2 if exist "WinRE_Backup\winre.wim" goto :skipBackupWinRE
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End

:WinREWimNotFound
echo.
echo Error: The 'winre.wim' file could not be found.
echo.
call :SearchForWinRE
if %buildmode% EQU 2 if exist "WinRE_Backup\winre.wim" goto :skipBackupWinRE
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End

:DISMMountError
rd /s /q "%tbpath%\build" > nul
echo.
echo Error: Unable to mount winre.wim.
echo.
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End

:DISMSaveError
rd /s /q "%tbpath%\build" > nul
echo.
echo Error: Unable to successfully save WinRE image.
echo.
echo Script aborted.
echo.
tbutil -pause -m "Press any key to exit script..."
goto :End


:ViewTutorial
echo.
if exist "TBWinRE Tutorial.url" explorer "TBWinRE Tutorial.url" & goto :DisplayMenu
echo [InternetShortcut] > "TBWinRE Tutorial.url"
echo URL=http://www.terabyteunlimited.com/howto/tbwinre_tutorial.htm >> "TBWinRE Tutorial.url"
explorer "TBWinRE Tutorial.url"
goto :DisplayMenu


:ManageSettings
cls
echo.
echo ==============================================================================
echo   TeraByte WinRE Builder                                           ver. %tbwinre_ver%
echo ==============================================================================
echo.
echo Manage Saved Settings
echo.
echo Please make a selection from the following choices:
echo.
echo   1 - Save current build settings
echo       (Saved settings will be retained when script is updated.)
echo.
if exist savedsettings.ini (
	echo   2 - Delete saved settings
	echo.
	if %usesavedsettings% EQU 0 echo   3 - Toggle using saved settings for build [Current state: Disabled]
	if %usesavedsettings% EQU 1 echo   3 - Toggle using saved settings for build [Current state: Enabled]
	echo.
	echo   4 - Return to main menu
	echo.
	tbutil -choice -c 1234 -m "Press the number of your selection: "
) else (
	echo   2 - Return to main menu
	echo.
	tbutil -choice -c 12 -e 1,4 -m "Press the number of your selection: "
)
if %errorlevel% EQU 4 goto :DisplayMenu
if %errorlevel% EQU 3 (
	if %usesavedsettings% EQU 1 set /a usesavedsettings=0
	if %usesavedsettings% EQU 0 set /a usesavedsettings=1
	tbutil -iniwrite SavedSettings.ini -s Options -k UseSavedSettings -v !usesavedsettings!
	goto :ManageSettings
)
if %errorlevel% EQU 2 (del savedsettings.ini) & (set /a usesavedsettings=0)
if %errorlevel% EQU 1 (
	echo. & echo.
	tbutil -savebuildsettings
	if !errorlevel! EQU 0 echo Settings successfully saved.
	if !errorlevel! EQU 1 echo An error occurred while saving settings.
	echo.
	tbutil -pause
)
goto :ManageSettings


:: Function to search standard locations for winre.wim file (only for CD/UFD/ISO build)
:SearchForWinRE
if not %buildmode% EQU 2 goto :EOF
echo Searching for WinRE...
(set foundwinre=)

:: Search for Winre.wim
:: ---- Look in %recseqdrv%\Recovery, if valid
if "%recseqdrv%"=="" (set recseqdrv=zz)
if "%recseqdrv:~1,1%"==":" if exist "%recseqdrv%\Recovery" for /f "usebackq tokens=* delims=" %%G in (`dir /s /a /b %recseqdrv%\Recovery ^| find /i "winre.wim"`) do (set foundwinre=%%G)
:: ---- Look in %WinRE_VolGUID%\Recovery path, if valid
if "%WinRE_VolGUID%"=="" (set WinRE_VolGUID=zz)
if "%foundwinre%"=="" if "%WinRE_VolGUID:~0,4%"=="\\?\" for /f "usebackq tokens=* delims=" %%G in (`dir /s /a /b %WinRE_VolGUID%\Recovery ^| find /i "winre.wim"`) do (set foundwinre=%%G)
:: ---- Look in %SystemRoot%\System32\Recovery
if "%foundwinre%"=="" if exist "%SystemRoot%\System32\Recovery\winre.wim" set foundwinre=%SystemRoot%\System32\Recovery\winre.wim
:: ---- Look in %SystemDrive%\Recovery\...
if "%foundwinre%"=="" if exist "%SystemDrive%\Recovery" for /f "usebackq tokens=* delims=" %%G in (`dir /s /a /b %SystemDrive%\Recovery ^| find /i "winre.wim"`) do (set foundwinre=%%G)

:: Search for Winre.dat
:: ---- Look in %recseqdrv%\Recovery, if valid
if "%foundwinre%"=="" if "%recseqdrv:~1,1%"==":" if exist "%recseqdrv%\Recovery" for /f "usebackq tokens=* delims=" %%G in (`dir /s /a /b %recseqdrv%\Recovery ^| find /i "winre.dat"`) do (set foundwinre=%%G)
:: ---- Look in %WinRE_VolGUID%\Recovery path, if valid
if "%foundwinre%"=="" if "%WinRE_VolGUID:~0,4%"=="\\?\" for /f "usebackq tokens=* delims=" %%G in (`dir /s /a /b %WinRE_VolGUID%\Recovery ^| find /i "winre.dat"`) do (set foundwinre=%%G)
:: ---- Look in %SystemRoot%\System32\Recovery
if "%foundwinre%"=="" if exist "%SystemRoot%\System32\Recovery\winre.dat" set foundwinre=%SystemRoot%\System32\Recovery\winre.dat
:: ---- Look in %SystemDrive%\Recovery\...
if "%foundwinre%"=="" if exist "%SystemDrive%\Recovery" for /f "usebackq tokens=* delims=" %%G in (`dir /s /a /b %SystemDrive%\Recovery ^| find /i "winre.dat"`) do (set foundwinre=%%G)

:: If not found, abort
if "%foundwinre%"=="" echo WinRE not found. & echo. & goto :EOF
:: Copy found winre.wim to backup location and continue build
echo WinRE found. Saving backup...
if not exist "WinRE_Backup" md "WinRE_Backup"
(set foundwinreattr=)
(set foundwinreattrstr=)
for /f "usebackq tokens=* delims=" %%G in (`attrib "%foundwinre%"`) do (set foundwinreattr=%%G)
if "%foundwinreattr:~3,1%"=="S" (set foundwinreattrstr=+s)
if "%foundwinreattr:~4,1%"=="H" (set foundwinreattrstr=%foundwinreattrstr% +h)
attrib -s -h "%foundwinre%"
copy "%foundwinre%" "WinRE_Backup\Winre.wim" > nul
:: verify copy
fc /b "%foundwinre%" "WinRE_Backup\winre.wim" > nul
if errorlevel 1 (
	echo Backup failed. & echo.
	if exist "WinRE_Backup\winre.wim" del "WinRE_Backup\winre.wim"
	goto :EOF
)
if not "%foundwinreattrstr%"=="" attrib %foundwinreattrstr% "%foundwinre%"
attrib -r "WinRE_Backup\winre.wim"
(set WinRE_Path=%tbpath%\WinRE_Backup)
echo Backup created successfully. & echo.
goto :EOF


:: ---------------------
:: Final Script Cleanup
:: ---------------------

:End

endlocal
