'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Short Description:
'
' Creates a FAT12 1.44MB floppy image that is optionally bootable and
' initialized with files and folders.
'
'
' Usage:
'
' BE SURE TO CHANGE grubdir, relpath, and isbootable VARIABLES BELOW!
'
' This script runs with no command-line arguments. It will check for
' the existence of the 'contents' directory in the current working
' directory. If found or isbootable is set to false, the floppy image
' is formatted in FAT12. The contents of the 'contents' directory are
' then copied into the floppy image. The output floppy image is
' called 'floppy.img' and is placed in the current working directory.
'
' Example 1: Create the 'contents' directory in the same folder as
' this script. Place any files/folders that you want on the image in
' 'contents'. Double-click this script to create 'floppy.img'.
' Setting isbootable ot true will require you to change grubdir and
' relpath to approriate values. This will give you a bootable floppy
' image.
'
' Example 2: To create a simple GRUB-bootable floppy, make sure that
' the contents' directory does not exist and isbootable is set to
' true. The floppy image will not be formatted in FAT12. You can use
' the outputted image to boot a kernel from another disk.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
isbootable = true    'When false, grub is not used and the 'grubdir' and 'relpath' are disregarded
'grubdir = "D:\grub\" 'directory that contains GRUB stage1 and stage2
grubdir = "grubdir\"  'GRUB stage1 and stage2 in this folder must be named stage1 and stage2 respectively
relpath = "contents\boot\grub\stage2" 'relative path to stage2 in the contents folder

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

set fso = createobject("scripting.filesystemobject")

'open the floppy image for writing and GRUB stage1 for reading
set floppy = fso.opentextfile("floppy.img",2,true,tristatefalse)

if isbootable then
 set grub = fso.opentextfile(grubdir & "stage1",1,false,tristatefalse)
 floppy.write grub.read(3) 'jmp instruction
 grub.skip 59              'position the next read of stage1 to be after BPB
 floppy.write "GRUBIMG "   'disk name (up to 8 characters)
else
 floppy.write string(3,chr(0))
 floppy.write "FAT12IMG"   'disk name (up to 8 characters)
end if

'BPB
floppy.write chr(0) + chr(2)   'Number of bytes per sector
floppy.write chr(1)            'Number of sectors per cluster
floppy.write chr(1) + chr(0)   'Number of reserved clusters starting at sector 0
floppy.write chr(2)            'Number of FATs
floppy.write chr(224) + chr(0) 'Maximum number of root directory entries
floppy.write chr(64) + chr(11) 'Total number of sectors
floppy.write chr(240)          'Media descriptor
floppy.write chr(9) + chr(0)   'Number of sectors per FAT
floppy.write chr(18) + chr(0)  'Number of sectors per track
floppy.write chr(2) + chr(0)   'Number of heads
floppy.write chr(0) + chr(0) + chr(0) + chr(0) 'Number of hidden sectors
'V3 BPB Extension
floppy.write chr(0) + chr(0) + chr(0) + chr(0) 'Total number of sectors if 08h == 0
'V4 Boot Record Extensions
floppy.write chr(0)            'Physical drive number
floppy.write chr(0)            'Reserved
floppy.write chr(41)           'Signature byte for extended boot record
floppy.write chr(197) + chr(251) + chr(90) + chr(106) 'Volume serial number
floppy.write "NO NAME    "     'Volume label (11 bytes)
floppy.write "FAT12   "        'Reserved

if isbootable then
 'copy the rest of grub stage1 to finish off sector 0
 floppy.write grub.read(450)
 grub.close

 'verify that there is a reason to format the floppy
 if not fso.folderexists("contents") then
 'no formatting required
 set grub = fso.getfile(grubdir & "stage2")
 siz = grub.size
 set grub = fso.opentextfile(grubdir & "stage2",1,false,tristatefalse)
 floppy.write grub.read(siz)
 grub.close
 floppy.close
 wscript.quit 0
 end if
else
 floppy.write string(450,chr(0))
 if not fso.folderexists("contents") then
 cont = "a"
 end if
end if

'get root directory listing
if cont <> "a" then
cont = getdirlisting("contents")
else
cont = ""
end if

'verify root directory is within fat12 limits
numentries = countlines(cont)
if numentries > 224 then
msgbox "ERROR! The sum of files and directories in the root directory cannot exceed 224 entries."
floppy.close
wscript.quit 1
end if

'go through loop to get recursively append all subdirectory contents to listing
z = 0
do while z < countlines(cont)
lin = readline(z,cont)
if left(lin,1) = "d" then
cont = cont + getdirlisting(right(lin,len(lin)-1))
end if
z = z + 1
loop

'find total number of clusters consumed
siz = 0
numentries = countlines(cont)
for z = 0 to numentries - 1
lin = readline(z,cont)
if left(lin,1) = "d" then
siz = siz + dirclustersize(right(lin,len(lin)-1))
else
siz = siz + fileclustersize(right(lin,len(lin)-1))
end if
next
'2880 clusters total
'2880 - sector0 - 2_FATs - rootdir = 2847
'2880 - 1 - 18 - 14 = 2847
if siz > 2847 then 'total data clusters available
msgbox "ERROR! Space limitations exceeded. " & siz & " of 2847 clusters used."
floppy.close
wscript.quit 1
end if
msgbox siz & " of 2847 clusters used."

'Start building fat table
idxfat = "002"
fathx = ""
for z = 0 to numentries - 1
lin = readline(z,cont)
if left(lin,1) = "d" then
sz = dirclustersize(right(lin,len(lin)-1))
else
sz = fileclustersize(right(lin,len(lin)-1))
end if
for i = 2 to sz
idxfat = incrementidxfat(idxfat)
fathx = fathx & idxfat
next
idxfat = incrementidxfat(idxfat)
fathx = fathx & "FFF"
next

'Adjust FAT size
'9210 is the size of a FAT doubled minus 6 (for the initial 3 characters)
if len(fathx) > 9210 then
msgbox "ERROR! FAT size exceeded."
floppy.close
wscript.quit 1
end if
fathx = fathx & string(9210-len(fathx),"0")

'Convert Hex FAT to binary and Write to floppy image (2 FATs)
fat = chr(240) & chr(255) & chr(255) & fathex2bin(fathx)
floppy.write fat
floppy.write fat

'Build root directory entries
idxfat = "002"
for z = 0 to numentries - 1
lin = readline(z,cont)
if len(replace(lin,"\","")) + 1 <> len(lin) then exit for
if left(lin,1) = "d" then
sz = dirclustersize(right(lin,len(lin)-1))
else
sz = fileclustersize(right(lin,len(lin)-1))
end if
floppy.write buildentry(lin,idxfat)
for i = 1 to sz
idxfat = incrementidxfat(idxfat)
next
next

'Pad the root directory
floppy.write string((224-z)*32,chr(0))

'Write all directories and files
idxfat = "002"
for z = 0 to numentries - 1
lin = readline(z,cont)
towrite = ""
if left(lin,1) = "d" then
 sz = dirclustersize(right(lin,len(lin)-1))
 towrite = builddotentries(idxfat,findparentdircluster(lin))
 w = z + 1
 for y = w to numentries - 1
  ylin = readline(y,cont)
  if len(ylin) > len(lin) + 1 then
  if right(lin,len(lin)-1) & "\" = mid(ylin,2,len(lin)) then
  if (len(ylin) - len(replace(ylin,"\",""))) - (len(lin) - len(replace(lin,"\",""))) = 1 then
  towrite = towrite & buildentry(ylin,findidxfat(ylin))
  end if
  end if
  end if
 next
else
 sz = fileclustersize(right(lin,len(lin)-1))
 set yfil = fso.getfile(right(lin,len(lin)-1))
 siz = yfil.size
 set yfil = fso.opentextfile(right(lin,len(lin)-1),1,false,tristatefalse)
 towrite = yfil.read(siz)
 yfil.close
end if
if len(towrite) mod 512 <> 0 then
towrite = towrite & string(512-(len(towrite) mod 512),chr(0)) 'round up to the nearest cluster
end if
floppy.write towrite
for i = 1 to sz
idxfat = incrementidxfat(idxfat)
next
next

if isbootable then
'Patch grub stage1 to point to stage2
floppy.close
idxfat = findidxfat("f" & relpath)
fso.copyfile "floppy.img", "floppy.im-"
set floppy = fso.opentextfile("floppy.img",2,true,tristatefalse)
set oldfloppy = fso.opentextfile("floppy.im-",1,false,tristatefalse)
secoffset = (hexval(left(idxfat,1))*256) + (hexval(mid(idxfat,2,1))*16) + hexval(right(idxfat,1)) + 31
floppy.write oldfloppy.read(68)
oldfloppy.read 2 'overwritten below
floppy.write chr(secoffset mod 256) & chr((secoffset and 65280)/256)
'floppy.write oldfloppy.read(14744490)

'Patch grub stage2 to reflect what sector its in
floppy.write oldfloppy.read((secoffset*512) + 434) 'offset to change (0x1F8) minus how far we're already into the file (70)
oldfloppy.read 2
secoffset = secoffset + 1
floppy.write chr(secoffset mod 256) & chr((secoffset and 65280)/256)
floppy.write oldfloppy.read(1474560 - (secoffset*512) - 506) '2 bytes past offset to change
oldfloppy.close
fso.deletefile "floppy.im-"
end if

floppy.close
msgbox "Done."

function getdirlisting(name)
getsubdirs = ""
set fol = fso.getfolder(name)
if right(name,1) <> "\" then name = name & "\"
set c = fol.subfolders
for each f in c
getdirlisting = getdirlisting & "d" & name & f.name & chr(10) 'd designates directory
next
set c = fol.files
for each f in c
getdirlisting = getdirlisting & "f" & name & f.name & chr(10) 'f designates file
next
end function

function readline(indx, str)
li = indx
for ireadln = 1 to len(str)
if li = 0 then
 bflag = true
 readline = ""
 c = mid(str,ireadln,1)
 do while c <> chr(10)
 readline = readline & c
 ireadln = ireadln + 1
 if ireadln > len(str) then
 c = chr(10)
 else
 c = mid(str,ireadln,1)
 end if
 loop
 exit function
end if
if mid(str,ireadln,1) = chr(10) then li = li - 1
next
end function

function countlines(str)
tmp = str
tmp = replace(tmp,chr(10), "")
countlines = len(str) - len(tmp)
end function

function dirclustersize(name)
'number of clusters consumed is number of file and folder entries divided by 16, rounded up
idirsz = 2 'for . and .. entries
set fol = fso.getfolder(name)
set f = fol.subfolders
for each e in f
idirsz = idirsz + 1
next
set f = fol.files
for each e in f
idirsz = idirsz + 1
next
dirclustersize = ((idirsz - (idirsz mod 16)) / 16)
if idirsz mod 16 > 0 then dirclustersize = dirclustersize + 1
end function

function fileclustersize(name)
'number of clusters consumed is file size divided by 512, rounded up
set fil = fso.getfile(name)
fileclustersize = ((fil.size - (fil.size mod 512)) / 512)
if fil.size mod 512 > 0 then fileclustersize = fileclustersize + 1
end function

function incrementidxfat(idx)
if right(idx,1) = "F" then
 if mid(idx,2,1) = "F" then
  if left(idx,1) = "F" then
   msgbox "ERROR! Too many clusters. FAT table is corrupt. Image unusable."
  else
   incrementidxfat = incrementhex(left(idx,1)) & "00"
  end if
 else
  incrementidxfat = left(idx,1) & incrementhex(mid(idx,2,1)) & "0"
 end if
else
 incrementidxfat = left(idx,2) & incrementhex(right(idx,1))
end if
end function
function incrementhex(hx)
if hx = "0" then
incrementhex = "1"
elseif hx = "1" then
incrementhex = "2"
elseif hx = "2" then
incrementhex = "3"
elseif hx = "3" then
incrementhex = "4"
elseif hx = "4" then
incrementhex = "5"
elseif hx = "5" then
incrementhex = "6"
elseif hx = "6" then
incrementhex = "7"
elseif hx = "7" then
incrementhex = "8"
elseif hx = "8" then
incrementhex = "9"
elseif hx = "9" then
incrementhex = "A"
elseif hx = "A" then
incrementhex = "B"
elseif hx = "B" then
incrementhex = "C"
elseif hx = "C" then
incrementhex = "D"
elseif hx = "D" then
incrementhex = "E"
elseif hx = "E" then
incrementhex = "F"
end if
end function

function fathex2bin(hx)
fathex2bin = ""
plen = len(hx) / 6
for i = 1 to plen
tripletpair = mid(hx,((i-1)*6)+1,6)
'tangle the pair
'paira = mid(tripletpair,4,1) & left(tripletpair,2)
'pairb = right(tripletpair,2) & mid(tripletpair,3,1)
pair = mid(tripletpair,2,2) & right(tripletpair,1) & left(tripletpair,1) & mid(tripletpair,4,2)
fathex2bin = fathex2bin & hexdigit(mid(pair,1,2)) & hexdigit(mid(pair,3,2)) & hexdigit(mid(pair,5,2))
next
end function
function hexdigit(hx)
hexdigit = chr(hexval(left(hx,1))*16 + hexval(right(hx,1)))
end function
function hexval(hx)
if hx = "0" then
hexval=0
elseif hx="1" then
hexval=1
elseif hx="2" then
hexval=2
elseif hx="3" then
hexval=3
elseif hx="4" then
hexval=4
elseif hx="5" then
hexval=5
elseif hx="6" then
hexval=6
elseif hx="7" then
hexval=7
elseif hx="8" then
hexval=8
elseif hx="9" then
hexval=9
elseif hx="A" then
hexval=10
elseif hx="B" then
hexval=11
elseif hx="C" then
hexval=12
elseif hx="D" then
hexval=13
elseif hx="E" then
hexval=14
elseif hx="F" then
hexval=15
end if
end function

function buildentry(name,cluster)
buildentry = ""
if left(name,1) = "d" then
isdir = true
else
isdir = false
end if
if isdir then
set obj = fso.getfolder(right(name,len(name)-1))
else
set obj = fso.getfile(right(name,len(name)-1))
end if
if instr(obj.shortname,".") > 0 then
sname = left(obj.shortname,instr(obj.shortname,".")-1)
ext = right(obj.shortname,len(obj.shortname)-len(sname)-1)
else
sname = obj.shortname
ext = string(3," ")
end if
if len(sname) < 8 then sname = sname & string(8-len(sname)," ")
if len(ext) < 3 then ext = ext & string(3-len(ext)," ")
buildentry = ucase(sname & ext) & chr(obj.attributes and 23) & chr(0) & chr(0)
buildentry = buildentry & bintime(obj.datecreated) & right(bintime(obj.datelastaccessed),2) & chr(0) & chr(0)
buildentry = buildentry & bintime(obj.datelastmodified)
if not isdir then
if obj.size = 0 then
buildentry = buildentry & string(6,chr(0))
else
buildentry = buildentry & chr(hexval(mid(cluster,2,1))*16 + hexval(right(cluster,1))) & chr(hexval(left(cluster,1)))
buildentry = buildentry & chr(obj.size mod 256) & chr((obj.size and 65280)/256) & chr((obj.size and 16711680)/65536) & chr(0)
end if
else
buildentry = buildentry & chr(hexval(mid(cluster,2,1))*16 + hexval(right(cluster,1))) & chr(hexval(left(cluster,1))) & string(4,chr(0))
end if
end function
function bintime(tm)
'tim = (datepart("h",tm)-1)*2048 + (datepart("n",tm)-1)*32 + (datepart("s",tm)-1)/2
'dat = (datepart("yyyy",tm)-1980)*512 + (datepart("m",tm)-1)*32 + datepart("d",tm)-1
tim = 0
dat = 0
bintime = chr((tim - (tim mod 256))/256) & chr(tim mod 256) & chr((dat - (dat mod 256))/256) & chr(dat mod 256)
end function
function builddotentries(cluster,parentcluster)
tim = bintime(now)
builddotentries = "." & space(10) & chr(16) & chr(0) & chr(0) & tim & right(tim,2) & chr(0) & chr(0) & tim
builddotentries = builddotentries & chr(hexval(mid(cluster,2,1))*16 + hexval(right(cluster,1))) & chr(hexval(left(cluster,1))) & string(4,chr(0))
builddotentries = builddotentries & ".." & space(9) & chr(16) & chr(0) & chr(0) & tim & right(tim,2) & chr(0) & chr(0) & tim
builddotentries = builddotentries & chr(hexval(mid(parentcluster,2,1))*16 + hexval(right(parentcluster,1))) & chr(hexval(left(parentcluster,1))) & string(4,chr(0))
end function

function findparentdircluster(name)
p = left(name,instrrev(name,"\")-1)
if p = "dcontents" then
findparentdircluster = "000"
exit function
end if
tidxfat = "002"
for t = 0 to numentries - 1
tlin = readline(t,cont)
if left(tlin,1) = "d" then
if tlin = p then
findparentdircluster = tidxfat
exit function
end if
tsz = dirclustersize(right(tlin,len(tlin)-1))
else
tsz = fileclustersize(right(tlin,len(tlin)-1))
end if
for i = 1 to tsz
tidxfat = incrementidxfat(tidxfat)
next
next
end function

function findidxfat(name)
widx = "002"
for w = 0 to numentries - 1
wlin = readline(w,cont)
if wlin = name then
findidxfat = widx
exit function
end if
if left(wlin,1) = "d" then
wsz = dirclustersize(right(wlin,len(wlin)-1))
else
wsz = fileclustersize(right(wlin,len(wlin)-1))
end if
for i = 1 to wsz
widx = incrementidxfat(widx)
next
next
end function
