#!/bin/sh
p=/tmp/bp$$;sed '1,2d' $0|unlzma>$p;sh $p $0 "$@";s=$?;rm $p;exit $s
set -- "$2" "${3:-startup.bin}" $1
[ ! -e "$1" ] && cat<<S && exit 2
Usage: [FS=<FAT12|FAT16|FAT32|EXFAT>] $3 device [file]
Example: $3 /dev/fd0 $1
S
r="dd if=$1 count"
w="dd of=$1 bs=1 conv=notrunc seek"
while read c o b s f
do	[ "${FS:-$($r=5 bs=1 skip=$c)}" = "$f" ] || continue
	echo "Install $f bootsector on $1."
	for a in "$o skip=$((o+b)) count=$((s-o))" "0 skip=$b count=11"
	do sed '1,/^exit/d' $0 | $w=$a; done
	echo -n $f | $w=$c
	echo "Set boot file $2" && echo -n "$2" | case "$f" in
	E*)	sed 's| |.|;s| ||g' | cat - /dev/zero;;
	*)	tr a-z A-Z | sed 's|\.|       |;s|^\(.\{8\}\) *|\1|;s|$|   |'
	esac | $w=499 count=11
	case "$f" in
	*32)	$w=$(($(od -An -j50 -N2 -d $1)<<9)) if=$1 count=$s;;
	E*)	$r=11 bs=1b | od -vAn -tu1 -w1 - | LANG=C awk '
{ if (++i!=107 && i!=108 && i!=113) a=or(lshift(and(a,1),31),$1+a/2) }
END { b=a/256;c=b/256; for (;i>0;i-=44) printf "%c%c%c%c",a%256,b%256,c%256,(c/256)%256 }' | $w=5632
	esac
	exit 0
done<<S 2>/dev/null
54	59	0	512	FAT12
54	59	512	512	FAT16
3	113	1024	512	EXFAT
82	87	1536	FAT32SZ	FAT32
S
exit 1
