:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see "https://stackoverflow.com/a/12264592/1016343" for description
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@echo off
set caption=Fastoe Bootable USB Drive Recovery Utility
title %caption%
cls

:init
  setlocal DisableDelayedExpansion
  set cmdInvoke=1
  set winSysFolder=System32
  set "batchPath=%~dpnx0"
  rem this works also from cmd shell, other than %~0
  for %%k in (%0) do set batchName=%%~nk
  set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
  setlocal EnableDelayedExpansion

:checkPrivileges
  NET FILE 1>NUL 2>NUL
  if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges
  if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
  echo.
  echo ***********************************************************************
  echo Invoking UAC for Privilege Escalation
  echo ***********************************************************************

  echo Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
  echo args = "ELEV " >> "%vbsGetPrivileges%"
  echo For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
  echo args = args ^& strArg ^& " "  >> "%vbsGetPrivileges%"
  echo Next >> "%vbsGetPrivileges%"
  
  if '%cmdInvoke%'=='1' goto InvokeCmd 

  echo UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
  goto ExecElevation

:InvokeCmd
  echo args = "/c """ + "!batchPath!" + """ " + args >> "%vbsGetPrivileges%"
  echo UAC.ShellExecute "%SystemRoot%\%winSysFolder%\cmd.exe", args, "", "runas", 1 >> "%vbsGetPrivileges%"

:ExecElevation
  "%SystemRoot%\%winSysFolder%\WScript.exe" "%vbsGetPrivileges%" %*
  exit /B

:gotPrivileges
  setlocal & cd /d %~dp0
  if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul  &  shift /1)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
if exist "%TEMP%\ConsoleSettingsBackup.reg" regedit /S "%TEMP%\ConsoleSettingsBackup.reg"&DEL /F /Q "%TEMP%\ConsoleSettingsBackup.reg" & goto :main
regedit /S /e "%TEMP%\ConsoleSettingsBackup.reg" "HKEY_CURRENT_USER\Console"
echo REGEDIT4>"%TEMP%\DisableQuickEdit.reg"
echo [HKEY_CURRENT_USER\Console]>>"%TEMP%\DisableQuickEdit.reg"
(echo "QuickEdit"=dword:00000000)>>"%TEMP%\DisableQuickEdit.reg"
regedit /S "%TEMP%\DisableQuickEdit.reg"
del /F /Q "%TEMP%\DisableQuickEdit.reg"
start "" "cmd" /c "%~dpnx0" & exit
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:main
@echo off
@set PATH=%CD%\tools\tcping;%PATH%
@set PATH=%CD%\tools\rufus;%PATH%
@set PATH=%CD%\tools\wget;%PATH%
@set PATH=%CD%\tools\7zip;%PATH%
setlocal enabledelayedexpansion
set errorinfo01=ERROR: The script can't start because tcping.exe is missing from your computer. Make sure all files are extracted to the same directory.
set errorinfo02=ERROR: The script can't start because rufus.exe is missing from your computer. Make sure all files are extracted to the same directory.
set errorinfo03=ERROR: The script can't start because wget.exe is missing from your computer. Make sure all files are extracted to the same directory.
set errorinfo04=ERROR: The script can't start because 7za.exe is missing from your computer. Make sure all files are extracted to the same directory.
if not exist "tools\tcping\tcping.exe" (
  echo. & echo %errorinfo01% & echo. & goto eof
)
if not exist "tools\rufus\rufus.exe" (
  echo. & echo %errorinfo02% & echo. & goto eof
)
if not exist "tools\wget\wget.exe" (
  echo. & echo %errorinfo03% & echo. & goto eof
)
if not exist "tools\7zip\7za.exe" (
  echo. & echo %errorinfo04% & echo. & goto eof
)
echo.
echo "+-------------------+"
echo "| Powered by Fastoe |"
echo "+-------------------+"
echo.
echo =======================================================================
echo Local storage
echo =======================================================================
set caption=Fastoe Bootable USB Drive Recovery Utility v2.22
set errorinfo11=ERROR: Failed to download OS list, please contact us at support@fastoe.com.
set errorinfo12=ERROR: Failed to download OS file, please contact us at support@fastoe.com.
set errorinfo13=ERROR: All servers are temporarily unavailable. Please email us at support@fastoe.com.
set errorinfo14=ERROR: Failed to extract image file. Please email us at support@fastoe.com.
set errorinfo15=ERROR: No Internet connection. Please check the network cables, modem, and router.
title %caption%
:start
set user=
set model=
set capacity=
set filename=%~n0
set partitions=
set verbose=0
set debug=0
set temp1=
set temp2=
set temp3=

set capacity=32gb

set current_drive_letter=%CD:~0,2%
for /f "tokens=3 usebackq" %%f in (`dir /-c /w %current_drive_letter%`) do set "size=%%f"
if !size! gtr 0 set size=!size:~0,-6!
if "!size!" == "" set size=0
set current_drive_free_in_b=!size!
set /a current_drive_free_in_gb=%current_drive_free_in_b% / 1024

echo Current drive letter  : %current_drive_letter%
echo Free space of %CD:~0,1% drive : !current_drive_free_in_gb! GB

set required_disk_space_in_gb=!capacity:~0,-2!
set /a required_disk_space_in_gb=%required_disk_space_in_gb% * 2
if !current_drive_free_in_gb! lss !required_disk_space_in_gb! (
  echo -----------------------------------------------------------------------
  echo ERROR: At least !required_disk_space_in_gb! GB of free disk space is required.
  echo.
  ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  for %%p in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
    if exist %%p:\nul (
      set drive_letter=%%p:
      for /f "tokens=3 usebackq" %%f in (`dir /-c /w !drive_letter!`) do set "size=%%f"
      if !size! gtr 0 set size=!size:~0,-6!
      if "!size!" == "" set size=0
      set drive_free_in_b=!size!
      set /a drive_free_in_gb=!drive_free_in_b! / 1024
      if !drive_free_in_gb! gtr !required_disk_space_in_gb! (
        set partitions=!partitions! !drive_letter!
      )
    )
  )
  if [!partitions!]==[] (
    echo.
  ) else (
    echo The following partitions have enough free space. Please move the script
    echo folder to any of the following partitions and run it again.
    echo  !partitions!
    echo.
  )
  goto eof
)

echo Required disk space   : !required_disk_space_in_gb! GB
echo =======================================================================
echo Downloading OS list...
echo =======================================================================
echo Please wait
if "%debug%" equ "1" (
  ping 127.0.0.1 -n 19 -w 1000 > nul
)
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set hosts[0]=roms1.fastoe.com
set hosts[1]=roms2.fastoe.com
set g_host=

set base_dir=%~dp0
if "%base_dir:~-1%" == "\" (
  set base_dir=%base_dir:~0,-1%
)
echo Current path          : %base_dir%
rd /q /s "%base_dir%\tmp" 2>nul
mkdir "%base_dir%\tmp"
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
echo -----------------------------------------------------------------------
echo - Checking Internet Connection
echo -----------------------------------------------------------------------
set time=999
for /f "tokens=*" %%a in ('tcping -n 3 www.github.com ^| find "Average"') do (set time=%%a )
set time=!time:ms=!
set time=!time: =!
set /a time+=1
set /a time-=1
if "!time!" equ "999" (
    echo. & echo %errorinfo15% & echo. & goto eof
) else (
    echo - Connected to the Internet. & echo.
)
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
for /f "tokens=2 delims==" %%a in ('set hosts[') do (
    set host=%%a
    tcping -n 3 !host! | find "Average" > !host!.log
    for /f "usebackq" %%b in ('!host!.log') do set size=%%~zb
    if "!size!" equ "0" (
        set time=999
        set /a time=!time! + 1
        set /a time=!time! - 1
    ) else (
        for /f "tokens=4 delims==" %%c in (!host!.log) do (
            set time=%%c
            set time=!time:ms=!
            set time=!time: =!
            set /a time+=1
            set /a time-=1
        )
    )
    if "!verbose!" equ "0" (
        del /f /s /q !host!.log 1>nul
    )
    if "!time!" neq "999" (
        echo !host! > tmp/!time!
    )
)

set i=0
for /f "tokens=*" %%a in ('dir /b /a-d tmp') do (
    set name=%%~nxa
    set /a i+=1
    for /f "tokens=*" %%b in (tmp\!name!) do ( set host=%%b )
    set host=!host: =!
    set hosts2[!i!]=!host!
)
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
if not exist "images" mkdir images

set idx=%i%
set flag=0
set flag2=0
for /l %%i in (1,1,%idx%) do (
  set host=!hosts2[%%i]!
  if "%debug%" equ "1" (
    set host=192.168.101.251:8080
    echo Host: !host!
  )
  set lst_name=os_list
  if "%filename%" equ "FastoeRecoveryUtility4Win11" (
    set lst_name=os_win11
    set flag2=11
  )
  if "%filename%" equ "FastoeRecoveryUtility4Win1032" (
    set lst_name=os_win1032
    set flag2=1032
  )
  if "%filename%" equ "FastoeRecoveryUtility4Win10" (
    set lst_name=os_win10
    set flag2=10
  )
  if "%filename%" equ "FastoeRecoveryUtility4Win81" (
    set lst_name=os_win81
    set flag2=81
  )
  if "%filename%" equ "FastoeRecoveryUtility4Win7" (
    set lst_name=os_win7
    set flag2=7
  )
  set lst_path=images\!lst_name!
  set lst_url=http://!host!/img/!lst_name!
  if exist "!lst_path!" del /f /s /q !lst_path! 1>nul
  if "!verbose!" equ "1" (
    wget -t 10 -c --show-progress -P images !lst_url!
  ) else (
    wget -t 10 -c -q --show-progress -P images !lst_url!
  )
  if exist "!lst_path%!" (
    set g_host=!host!
    goto pre-download
  )
  set /a flag+=1
)

if "%flag%" equ "%idx%" (
  echo. & echo %errorinfo13% & echo. & goto eof
)
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:pre-download
if "%debug%" equ "1" (
  set g_host=192.168.101.251:8080
)
ping 127.0.0.1 -n 1 -w 1000 > nul
cls
echo.
echo "+-------------------+"
echo "| Powered by Fastoe |"
echo "+-------------------+"
echo.
echo =======================================================================
echo - Setp 1 / 3: Choose an operating system
echo =======================================================================
set idx=1
set range=
echo.
echo Operating System:
for /f "tokens=1" %%a in (%lst_path%) do (
  if "%%a" equ "win11"   ( echo   !idx!^) Windows 11  16GB ^(64-bit^) )
  if "%%a" equ "win1032" ( echo   !idx!^) Windows 10  32GB ^(64-bit ^& 32-bit^) )
  if "%%a" equ "win10"   ( echo   !idx!^) Windows 10  16GB ^(64-bit ^& 32-bit^) )
  if "%%a" equ "win81"   ( echo   !idx!^) Windows 8.1 16GB ^(64-bit ^& 32-bit^) )
  if "%%a" equ "win7"    ( echo   !idx!^) Windows 7   16GB ^(64-bit ^& 32-bit^) )
  set range=!range!!idx!
  set /a idx+=1
)
echo.

choice /C !range! /M "Enter your choice:"

if !flag2! equ 0 (
  if "%ERRORLEVEL%" equ "1" (
    set os_ver=win11
    set os_dsc=Windows 11
  )
  if "%ERRORLEVEL%" equ "2" (
    set os_ver=win1032
    set os_dsc=Windows 10 32GB
  )
  if "%ERRORLEVEL%" equ "3" (
    set os_ver=win10
    set os_dsc=Windows 10
  )
  if "%ERRORLEVEL%" equ "4" (
    set os_ver=win81
    set os_dsc=Windows 8.1
  )
  if "%ERRORLEVEL%" equ "5" (
    set os_ver=win7
    set os_dsc=Windows 7
  )
) else (
  if !flag2! equ 11 (
    set os_ver=win11
    set os_dsc=Windows 11
  )
  if !flag2! equ 1032 (
    set os_ver=win1032
    set os_dsc=Windows 10
  )
  if !flag2! equ 10 (
    set os_ver=win10
    set os_dsc=Windows 10
  )
  if !flag2! equ 81 (
    set os_ver=win81
    set os_dsc=Windows 8.1
  )
  if !flag2! equ 7 (
    set os_ver=win7
    set os_dsc=Windows 7
  )
)
set os_ver=!os_ver: =!
echo.
echo Your choice: !os_dsc!
ping 127.0.0.1 -n 3 -w 1000 > nul
cls

:download
cls
echo.
echo "+-------------------+"
echo "| Powered by Fastoe |"
echo "+-------------------+"
echo.
echo =======================================================================
echo - Setp 2 / 3: Downloading !os_dsc! image...
echo =======================================================================
set sum_name=latest
set sum_path=images\%os_ver%\%sum_name%
set sum_url=http://%g_host%/img/%os_ver%/latest

if not exist "images" mkdir images
if exist "%sum_path%" del /f /s /q !sum_path! 1>nul

if "%verbose%" equ "1" (
  wget -t 10 -c --show-progress -P images/%os_ver% %sum_url%
) else (
  wget -t 10 -c -q --show-progress -P images/%os_ver% %sum_url%
)

if not exist "%sum_path%" (
  echo. & echo %errorinfo12% & echo. & goto eof
)
echo ***********************************************************************
echo We're doing our work behind the scenes. Feel free to keep working, and we'll
echo let you know when everything is done.
echo ***********************************************************************
wget -q http://%g_host%/img/%os_ver%/ping-na%ms1%-eu%ms2%

if "%verbose%" equ "1" (
  for /f "tokens=*" %%a in ('dir /b /a-d tmp') do (
    set name=%%~nxa
    set /a i+=1
    for /f "tokens=*" %%b in (tmp\!name!) do ( set host=%%b )
    set host=!host: =!
    echo !host!: !name!
  )
  echo Server: %host%
  echo -----------------------------------------------------------------------
)

set total=-1
for /f "tokens=1,2" %%a in (%sum_path%) do (
  set /a total+=1
)
set i=0
for /f "tokens=1,2" %%a in (%sum_path%) do (
  set tmp1_hash=%%a
  set part_file=%%b
  set part_file=!part_file: =!
  if !i! gtr 0 (
    set url=http://%g_host%/img/%os_ver%/!part_file!
    echo !i! / !total!
    if "%verbose%" equ "1" (
      wget -t 10 -c --show-progress -P images/%os_ver% !url!
    ) else (
      wget -t 10 -c -q --show-progress -P images/%os_ver% !url!
    )
  )
  set /a i+=1
)
cls
echo.
echo "+-------------------+"
echo "| Powered by Fastoe |"
echo "+-------------------+"
echo.
echo =======================================================================
echo - Setp 3 / 3: Verify and extract image file ^(!os_dsc!^)
echo =======================================================================
title %caption%
set img_hash=
set img_file=
set i=0
:: Get image hash and path
for /f "tokens=1,2" %%a in (%sum_path%) do ( 
  set tmp1_hash=%%a
  set tmp1_hash=!tmp1_hash: =!
  set part_file=%%b
  set part_file=images\%os_ver%\!part_file!
  if !i! equ 0 (
    set img_hash=!tmp1_hash!
    set img_file=!part_file!
  )
  set /a i+=1
)
if "%verbose%" equ "1" (
  echo Image hash: !img_hash!
  echo Image path: !img_file!
)

set flag=0
echo Verify integrity of OS image files, this may take some time.
if exist "!img_file!" (
  7za h -scrcsha256 !img_file! | find "SHA256 for data" > !img_file!.tmp
  for /f "tokens=4" %%a in (!img_file!.tmp) do set "tmp_hash=%%a"
  if "!tmp_hash!" equ "!img_hash!" (
    echo Verification success.
    wget -q http://%g_host%/img/%os_ver%/successful2
  ) else (
    set flag=1
    del /f /s /q !img_file! 1>nul
  )
) else (
  set flag=1
)
set retry=0
set i=0
if !flag! equ 1 (
  for /f "tokens=1,2" %%a in (%sum_path%) do ( 
    set tmp1_hash=%%a
    set tmp1_hash=!tmp1_hash: =!
    set part_file=%%b
    set part_file=images\%os_ver%\!part_file!
    if !i! equ 0 (
      set img_hash=!tmp1_hash!
      set img_file=!part_file!
    ) else (
      if exist "!part_file!" (
        7za h -scrcsha256 !part_file! | find "SHA256 for data" > !part_file!.tmp
        ping 127.0.0.1 -n 3 -w 1000 >nul
        for /f "tokens=4" %%a in (!part_file!.tmp) do ( set tmp2_hash=%%a )
        set tmp2_hash=!tmp2_hash: =!
        if "!tmp1_hash!" neq "!tmp2_hash!" (
          del  !img_file!.sha256 >NUL 2>&1
          del !part_file!
          set retry=1
          echo !part_file! [ Corrupted ]
        ) else (
          echo !part_file! [ OK ]
        )
        del !part_file!.tmp
      ) else (
        if "%verbose%" equ "1" (
          echo !part_file! [ Not Exist ]
        )
        set retry=1
      )
    )
    set /a i+=1
  )
  if "%verbose%" equ "1" (
    echo Retry: !retry!
  )
  if !retry! equ 1 (
    goto download
  )
  7za e !img_file!.7z.001 -oimages\%os_ver% -pHQX3dAWS6DKA
  7za h -scrcsha256 !img_file! | find "SHA256 for data" > !img_file!.tmp
  if not exist "!img_file!" (
    echo. & echo %errorinfo14% & echo. & goto eof
  )
  for /f "tokens=4" %%a in (!img_file!.tmp) do set "tmp_hash=%%a"
  if "%verbose%" equ "1" (
    echo Hash1: !img_hash!
    echo Hash2: !tmp_hash!
  )
  if "!tmp_hash!" equ "!img_hash!" (
    echo:
    echo -----------------------------------------------------------------------
    echo Verification success.
    wget -q http://%g_host%/img/%os_ver%/successful1
  ) else (
    del /f /s /q !img_file! 1>nul
    echo:
    echo -----------------------------------------------------------------------
    echo SHA256 checksum does not match.
    wget -q http://%g_host%/img/%os_ver%/failed
    goto eof
  )
)
cls
echo =======================================================================
echo - Setp: Factory reset
echo =======================================================================
echo Connect the USB flash drive to your computer, follow the prompts to
echo select the USB flash drive you inserted (keep other options as default)
echo and click START button.
echo:
set img_file_full_path=%cd%\!img_file!
pushd tools\rufus
  rufus --gui --iso=%img_file_full_path%
popd
:eof
pause