::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: 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 Tool
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 - Downloading OS list...
echo =======================================================================
set caption=Fastoe Bootable USB Drive Recovery Tool v2.11
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.
title %caption%
:start
set user=
set model=
set capacity=
set partitions=
set verbose=0
set debug=0
set temp1=
set temp2=
set temp3=

set capacity=16gb

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 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 -----------------------------------------------------------------------
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
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%
)
rd /q /s "%base_dir%\tmp" 2>nul
mkdir "%base_dir%\tmp"

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 /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
for /l %%i in (1,1,%idx%) do (
    set host=!hosts2[%%i]!
    if "%debug%" equ "1" (
        set host=192.168.101.251
    )
    set lst_name=os_list
    set lst_path=images\!lst_name!
    set lst_url=http://!host!/iso/!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
)
ping 127.0.0.1 -n 1 -w 1000 > nul
cls
echo =======================================================================
echo - Setp 1 / 3: Choose OS
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  ^(64-bit^) )
    if "%%a" equ "win10"      ( echo   !idx!^) Windows 10  ^(64-bit ^& 32-bit^) )
    if "%%a" equ "win81"      ( echo   !idx!^) Windows 8.1 ^(64-bit ^& 32-bit^) )
    if "%%a" equ "win7"       ( echo   !idx!^) Windows 7   ^(64-bit ^& 32-bit^) )
    if "%%a" equ "winxp"      ( echo   !idx!^) Windows XP  ^(32-bit^) )
    if "%%a" equ "winpe"      ( echo   !idx!^) Windows PE  ^(Hiren's PE^) )
    if "%%a" equ "ubuntu2204" ( echo   !idx!^) Ubuntu 22.04 Desktop ^(64-bit^) )
    if "%%a" equ "ubuntu2004" ( echo   !idx!^) Ubuntu 20.04 Desktop ^(64-bit^) )
    set range=!range!!idx!
    set /A idx+=1
)
echo.

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

if "%ERRORLEVEL%" equ "1" (
    set os_ver=win11
    set os_dsc=Windows 11
)
if "%ERRORLEVEL%" equ "2" (
    set os_ver=win10
    set os_dsc=Windows 10
)
if "%ERRORLEVEL%" equ "3" (
    set os_ver=win81
    set os_dsc=Windows 8.1
)
if "%ERRORLEVEL%" equ "4" (
    set os_ver=win7
    set os_dsc=Windows 7
)
if "%ERRORLEVEL%" equ "5" (
    set os_ver=winxp
    set os_dsc=Windows XP
)
if "%ERRORLEVEL%" equ "6" (
    set os_ver=winpe
    set os_dsc=Windows PE ^(Hiren's PE^)
)
if "%ERRORLEVEL%" equ "7" (
    set os_ver=ubuntu2204
    set os_dsc=Ubuntu 22.04 Desktop
)
if "%ERRORLEVEL%" equ "8" (
    set os_ver=ubuntu2004
    set os_dsc=Ubuntu 20.04 Desktop
)
set os_ver=!os_ver: =!
echo.
echo Your choice: !os_dsc!
ping 127.0.0.1 -n 3 -w 1000 > nul
cls

:download
echo =======================================================================
echo - Setp 2 / 3: Downloading !os_dsc! files...
echo =======================================================================
set sum_name=latest
set sum_path=images\%os_ver%\%sum_name%
set sum_url=http://%g_host%/iso/%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%/iso/%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%/iso/%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 - Setp 2 / 3: Verify and extract image file
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 file, 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%/iso/%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%/iso/%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%/iso/%os_ver%/failed
        goto eof
    )
)
echo =======================================================================
echo - Setp 3 / 3: Reimage
echo =======================================================================
echo Connect the USB flash drive to your computer, follow the
echo prompts to select the USB flash drive you inserted 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