#!/usr/bin/perl
## -----------------------------------------------------------------------
##
##   Copyright 2002-2007 H. Peter Anvin - All Rights Reserved
##
##   This program is free software; you can redistribute it and/or modify
##   it under the terms of the GNU General Public License as published by
##   the Free Software Foundation, Inc., 53 Temple Place Ste 330,
##   Boston MA 02111-1307, USA; either version 2 of the License, or
##   (at your option) any later version; incorporated herein by reference.
##
## -----------------------------------------------------------------------

#
# Creates a blank MS-DOS formatted hard disk image
#

use bytes;
use integer;
use Fcntl;
use Errno;
use Cwd;
use IO::Handle;			# For flush()

sub absolute_path($) {
    my($f) = @_;
    my($c);

    return $f if ( $f =~ /^\// );
    $c = cwd();
    $c = '' if ( $c eq '/' );
    return $c.'/'.$f;
}

sub is_linux() {
    return !!eval '{ '.
	'use POSIX; '.
	'($sysname, $nodename, $release, $version, $machine) = POSIX::uname(); '.
	"return \$sysname eq \'Linux\'; }";
}


$is_linux = is_linux();
if ( $is_linux ) {
    # IOCTL numbers
    $BLKRRPART    = 0x125f;
    $BLKGETSIZE   = 0x1260;
}

%opt = ();
@args = ();

for $a ( @ARGV ) {
    if ( $a =~ /^\-/ ) {
	foreach $o ( split(//, substr($a,1)) ) {
	    $opt{$o} = 1;
	}
    } else {
	push(@args, $a);
    }
}

($file,$c,$h,$s) = @args;
$c += 0;  $h += 0;  $s += 0;

$pentry = 1;
$pentry = 2 if ( $opt{'2'} );
$pentry = 3 if ( $opt{'3'} );
$pentry = 4 if ( $opt{'4'} );

if ( $opt{'z'} ) {
    $h = $h || 64;
    $s = $s || 32;
}

if ( $opt{'M'} && $h && $s ) {
    # Specify size in megabytes, not in cylinders
    $c = ($c*1024*2)/($h*$s);
}

$is_open = 0;

if ( $c == 0 && $file ne '' ) {
    $len = 0;
    if ( sysopen(OUTPUT, $file, O_RDWR, 0666) ) {
	$is_open = 1;

	if ( (@filestat = stat(OUTPUT)) && S_ISREG($filestat[2]) ) {
	    $len = $filestat[7] >> 9;
	} elsif ( $is_linux && S_ISBLK($filestat[2]) ) {
	    $blksize = pack("L!", 0);
	    if ( ioctl(OUTPUT, $BLKGETSIZE, $blksize) == 0 ) {
		$len = unpack("L!", $blksize); # In 512-byte sectors!
	    }
	}
    }

    if ( !$len ) {
	print STDERR "$0: $file: don't know how to determine the size of this device\n";
	exit 1;
    }

    $c = $len/($h*$s);
}

if ( $file eq '' || $c < 1 || $c > 1024 ||
     $h < 1 || $h > 256 || $s < 1 || $s > 63 ) {
    print STDERR "Usage: $0 [-doFMz4] file c h s (max: 1024 256 63)\n";
    print STDERR "    -d    add DOSEMU header\n";
    print STDERR "    -o    print filesystem offset to stdout\n";
    print STDERR "    -F    format partition as FAT32\n";
    print STDERR "    -M    \"c\" argument is megabytes, calculate cylinders\n";
    print STDERR "    -z    use zipdisk geometry (h=64 s=32)\n";
    print STDERR "    -4    use partition entry 4 (standard for zipdisks)\n";
    exit 1;
}

$cylsize = $h*$s*512;

if ( !$is_open ) {
    sysopen(OUTPUT, $file, O_CREAT|O_RDWR|O_TRUNC, 0666)
	or die "$0: Cannot open: $file\n";
}
binmode OUTPUT;

# Print out DOSEMU header, if requested
if ( $opt{'d'} ) {
    $emuhdr = "DOSEMU\0" . pack("VVVV", $h, $s, $c, 128);
    $emuhdr .= "\0" x (128 - length($emuhdr));
    print OUTPUT $emuhdr;
}

# Print the MBR and partition table
$mbr = '';
while ( $line = <DATA> ) {
    chomp $line;
    foreach $byte ( split(/\s+/, $line) ) {
	$mbr .= chr(hex($byte));
    }
}
if ( length($mbr) > 446 ) {
    die "$0: Bad MBR code\n";
}

$mbr .= "\0" x (446 - length($mbr));

print OUTPUT $mbr;

# Print partition table
$psize = $c*$h*$s-$s;
$bhead   = ($h > 1) ? 1 : 0;
$bsect   = 1;
$bcyl    = ($h > 1) ? 0 : 1;
$ehead   = $h-1;
$esect   = $s + ((($c-1) & 0x300) >> 2);
$ecyl    = ($c-1) & 0xff;
if ( $psize > 65536 ) {
    $fstype = 0x06;
} else {
    $fstype = 0x04;
}
for ( $i = 1 ; $i <= 4 ; $i++ ) {
    if ( $i == $pentry ) {
	print OUTPUT pack("CCCCCCCCVV", 0x80, $bhead, $bsect, $bcyl, $fstype,
			  $ehead, $esect, $ecyl, $s, $psize);
    } else {
	print OUTPUT "\0" x 16;
    }
}
print OUTPUT "\x55\xaa";

# Output blank file
$totalsize = $c*$h*$s;
$tracks    = $c*$h;

$track = "\0" x (512*$s);

# Print fractional track
print OUTPUT "\0" x (512 * ($s-1));

for ( $i = 1 ; $i < $tracks ; $i++ ) {
    print OUTPUT $track;
}

# Print mtools temp file
$n = 0;
while ( !defined($tmpdir) ) {
    $tmpdir = "/tmp/mkdiskimage.$$.".($n++);
    if ( !mkdir($tmpdir, 0700) ) {
	die "$0: Failed to make temp directory: $tmpdir\n"
	    if ( $! != EEXIST );
	undef $tmpdir;
    }
}

$cfgfile = $tmpdir.'/mtools.conf';
$imglink = $tmpdir.'/disk.img';
die "$0: Failed to create symlink $imglink\n"
    if ( !symlink(absolute_path($file), $imglink) );

$header_size = ($opt{'d'} ? 128 : 0);

# Start of filesystem
$offset = $s*512 + $header_size;

# Start of partition table entry
$pstart = $header_size + 446 + 16*($pentry-1);

open(MCONFIG, "> ${cfgfile}") or die "$0: Cannot make mtools config\n";
print MCONFIG "drive z:\n";
print MCONFIG "file=\"${imglink}\"\n";
print MCONFIG "cylinders=${c}\n";
print MCONFIG "heads=${h}\n";
print MCONFIG "sectors=${s}\n";
print MCONFIG "offset=${offset}\n";
print MCONFIG "mformat_only\n";
close(MCONFIG);

# Output the filesystem offset to stdout if appropriate
if ( $opt{'o'} ) {
    print $offset, "\n";
}

$ENV{'MTOOLSRC'} = $cfgfile;
if ( $opt{'F'} ) {
    system('mformat', '-F', 'z:');
} else {
    system('mformat', 'z:');
}

# Clean up in /tmp
unlink($cfgfile);
unlink($imglink);
rmdir($tmpdir);

# MTOOLS doesn't write the bsHiddenSecs field correctly
seek(OUTPUT, $offset + 0x1c, 0);
print OUTPUT pack("V", ($offset-$header_size)>>9);

# Set the partition type
if ( $opt{'F'} ) {
    $fstype = 0x0b;		# FAT32
} else {
    if ( $psize > 65536 ) {
	$fstype = 0x06;		# FAT16 > 32MB
    } else {
	$fstype = 0x04;		# FAT16 <= 32MB
    }
    seek(OUTPUT, $offset + 0x36, 0);
    read(OUTPUT, $fsname, 8);

    # FAT12: adjust partition type
    if ( $fsname eq 'FAT12   ' ) {
	$fstype = 0x01;		# FAT12
    }
}
seek(OUTPUT, $pstart+4, 0);
print OUTPUT pack("C", $fstype);

flush OUTPUT;

# Just in case this is a block device, try to flush the partition table
if ( $is_linux ) {
    ioctl(OUTPUT, $BLKRRPART, 0);
};

exit 0;
__END__
fa 31 c0 8e d8 8e d0 bc 0 7c 89 e6 6 57 52 8e c0 fb fc bf 0 6 b9 0 1 f3 a5 ea 20 6 0 0 52 b8 0 41 bb
aa 55 31 c9 30 f6 f9 cd 13 72 11 81 fb 55 aa 75 b f6 c1 1 74 6 c7 6 5f 6 eb 25 5a b4 8 cd 13 83 e1 3f 51
31 c0 88 f0 40 f7 e1 50 66 31 c0 66 50 66 50 e8 4f 0 e9 d4 0 66 89 c2 66 c1 ea 10 f7 36 f6 7b d0 cc d0 cc 88
e1 88 c5 89 d0 f6 36 f8 7b 88 c6 fe c4 8 e1 bb 0 7c b8 1 2 eb 9 be a8 7 66 89 44 8 b4 42 8a 16 fa 7b cd
13 c3 66 60 e8 c4 ff 72 b be be 7d bf be 7 b9 20 0 f3 a5 66 61 c3 60 89 e5 bf be 7 b9 4 0 31 c0 f6 5 80
74 3 40 89 fe 83 c7 10 e2 f3 83 f8 1 74 46 77 73 bf be 7 b1 4 8a 45 4 3c 5 74 8 3c f 74 4 3c 85 75 29
66 8b 45 8 66 8b 56 12 66 1 d0 66 21 d2 75 3 66 89 c2 66 50 66 52 e8 9e ff 72 3 e8 ae ff 83 c4 8 66 8b 46
16 e8 8f ff 83 c7 10 e2 c3 61 c3 66 8b 44 8 66 3 46 16 66 89 44 8 56 e8 41 ff 5e 72 17 81 3e fe 7d 55 aa 75
a bc fa 7b 5a 5f 7 fa e9 cd 74 be 55 7 eb 8 be 6f 7 eb 3 be 8c 7 ac 20 c0 74 c b4 e 8a 3e 62 4 b3 7
cd 10 eb ef cd 18 eb fe 4d 69 73 73 69 6e 67 20 6f 70 65 72 61 74 69 6e 67 20 73 79 73 74 65 6d 2e 0 4f 70 65
72 61 74 69 6e 67 20 73 79 73 74 65 6d 20 6c 6f 61 64 20 65 72 72 6f 72 2e 0 4d 75 6c 74 69 70 6c 65 20 61 63
74 69 76 65 20 70 61 72 74 69 74 69 6f 6e 73 2e 0 10 0 1 0 0 7c 0 0 0 0 0 0 0 0 0 0 
