@echo off
rem mbr install script
if "%2"=="subcall" goto sub1

echo ********************************************************************
echo * SPB-Linux mbr install script (requires administrator privileges) *
echo ********************************************************************
echo .
echo Looking for the last "harddrive" (highest number: 0,1,2..) in this computer...
echo (includes unremovable and removable storage media)
echo .

if exist flag.txt del flag.txt
if exist flag.txt goto write_err
echo writetest >flag.txt
if not exist flag.txt goto write_err
del flag.txt
goto write_ok
:write_err
echo error: to use this script you need write permission in the current directory
goto end
:write_ok

if not exist dd.exe goto files_err
if not exist spb2_mbr.sec goto files_err
goto files_ok
:files_err
echo error: required files, dd.exe and spb2_mbr.sec, not found
goto end
:files_ok

for %%n in (9 8 7 6 5 4 3 2 1 0) do call %0 %%n subcall
echo done
pause
goto end

:sub1
if exist flag.txt goto end
if not %1==0 goto next0
echo Warning: this mbr installer is written for removable media
echo          not for the primary harddisk (=physicaldrive0)
echo          - no other "harddisks" have been found
echo .
echo skipping installation of mbr bootloader (use fixmbr on the
echo recovery console instead of this script)
goto end
:next0
if exist hd%1_mbr.sec del hd%1_mbr.sec
dd if=\\.\physicaldrive%1 of=hd%1_mbr.sec bs=512 count=1 2>nul
if errorlevel 1 goto end
echo found%1 >flag.txt
rem NOT possible with nt/2k/XP: dd if=spb2_mbr.sec of=\\.\physicaldrive%1
copy spb2_mbr.sec spb2_mbr.tmp
rem filling unused bytes+ transferring partition table from old mbr to new mbr
rem size of bootloader code (spb2_mbr.sec) is <= 446 bytes:
dd if=hd2_mbr.sec of=spb2_mbr.tmp bs=1 count=512 skip=446 seek=446
echo the SPB-Linux 2 MBR bootloader (using LBA instead of CHS) will be installed now
echo .
echo do you REALLY want to WRITE sp2_mbr.tmp to the MBR of physicaldrive%1 ?
echo .
echo (press ctrl+c and then y to abort; any other key to continue)
pause
dd if=spb2_mbr.tmp of=\\.\physicaldrive%1
if errorlevel 1 echo error: failed to write the new mbr bootloader to physicaldrive%1
if errorlevel 1 goto end
echo the new mbr bootloader has been written to physicaldrive%1
echo (the original mbr has been copied to hd%1_mbr.sec and may be restored with
echo          dd if=hd%1_mbr.sec of=\\.\physicaldrive%1
echo warning: using dd with wrong parameters might make your system unbootable)
echo .
:end