#! /usr/bin/perl
use strict;
use warnings;
use bytes;
use Getopt::Long;
use Fcntl qw(SEEK_SET);


sub signature($$$$;$)
{
my($hay,$hay_filename,$offset,$needle,$msg)=@_;

	die if length($needle)%1;
	my $len_bytes=length($needle)/2;
	substr($hay,$offset,$len_bytes) eq pack("H*",$needle)
			or die "\"$hay_filename\" error reading signature 0x$needle @".sprintf("0x%X",$offset)
					.(!$msg ? "" : "; $msg")."\n";
}

my $BACKUP_SECTOR_START=63;
my $MAX_BOOT_SIZE=0x1b6;	# LILO: leave some space for NT's and DR DOS' dirty


my $bin_filename="./biosautoraid.bin";
my $opt_install;
my $opt_uninstall;
my $options_error=!GetOptions(
		"bin=s"      ,\$bin_filename,
		"i|install"  ,\$opt_install,
		"u|uninstall",\$opt_uninstall,
		);
local *BIN;
open BIN,$bin_filename or die "open \"$bin_filename\": $!";
my $bin=do { local $/; <BIN>; } or die "read \"$bin_filename\": $!";
close BIN or die "close \"$bin_filename\": $!";

my $bin_len=length($bin);
$bin_len>0 && !($bin_len%0x200) or die "Invalid length of \"$bin_filename\": $bin_len";
my $bin_short=($bin_len==0x200);	# => no 0xBEEF

signature $bin,$bin_filename,0x1FE     ,"55AA";
substr($bin,$MAX_BOOT_SIZE,0x1FE-$MAX_BOOT_SIZE)=~/^\x00*$/s or die "No empty magic+partitiontable: $bin_filename";

if (substr($bin,3,8) eq "BIOSRAID") {
	signature $bin,$bin_filename,0x03      ,unpack("H*","BIOSRAID");
	signature $bin,$bin_filename,0x43      ,"5E81A2".sprintf("%X",$BACKUP_SECTOR_START);
	signature $bin,$bin_filename,$bin_len-2,"BEEF" if !$bin_short;
	}
else {
	signature $bin,$bin_filename,0x03      ,unpack("H*","BIOSRAI2")
			.sprintf("%X%X",$BACKUP_SECTOR_START,$MAX_BOOT_SIZE-0x100);
	}

my $all_ok;
END {
	warn "Syntax: $0 [--bin=<biosautoraid.bin>] [{-i|--install|-u|--uninstall} <device>]" if !$all_ok;
	}

if (!@ARGV && !$options_error) {
	print "OK, \"$bin_filename\" checked.\n";
	$all_ok=1;
	exit 0;
	}

die "Type -i|--install or -u|--uninstall"                     if (!$opt_install && !$opt_uninstall) || $options_error;
die "Both -i|--install and -u|--uninstall forbidden together" if   $opt_install &&  $opt_uninstall;

@ARGV<=1 or die;
my $device_filename=$ARGV[0];

local *DEVICE;
open DEVICE,"+<".$device_filename or die "open \"$device_filename\": $!";

my $backup_offset=$BACKUP_SECTOR_START*0x200;

sysseek DEVICE,0,SEEK_SET or die "Error seeking $device_filename";
my $master;
$bin_len==sysread DEVICE,$master,$bin_len or die "read \"$device_filename\": $!";
length($master)==$bin_len or die "read \"$device_filename\": ".length($master)."!=$bin_len";
signature $master,$device_filename,0x1FE,"55AA";

sysseek DEVICE,$backup_offset,SEEK_SET or die "Error seeking $device_filename";
my $backup;
$bin_len==sysread DEVICE,$backup,$bin_len or die "read \"$device_filename\": $!";
length($backup)==$bin_len or die "read \"$device_filename\": ".length($backup)."!=$bin_len";

my $zeroes="\x00"x$bin_len;
die if length($zeroes)!=$bin_len;

$bin=substr($bin,0,$MAX_BOOT_SIZE).substr($master,$MAX_BOOT_SIZE,0x1FE-$MAX_BOOT_SIZE).substr($bin,0x1FE);

my $installed=substr($master,0x03,7) eq "BIOSRAI";
print "Already instaled? ".($installed ? "YES" : "NO")."\n";

die "Nothing to uninstall!\n" if $opt_uninstall && !$installed;

if ($installed) {
	signature $master,$device_filename,$bin_len-2,"BEEF","Different installed SECTOR_LEN?" if !$bin_short;
	signature $master,$device_filename,0x03      ,unpack("H*","BIOSRAI");
	signature $master,$device_filename,0x43      ,"5E81A2".sprintf("%X",$BACKUP_SECTOR_START) if !$bin_short;
	signature $backup,"backup",0x1FE,"55AA";
	}
if ($opt_install) {
	if (!$installed) {
		if ($backup ne $zeroes) {
			# Permit different DOS-volume area and 0x1FC..0x1FD bytes.
			die "Sensitive bytes at backup sectors" if !(1
				&& (0
					|| substr($backup,0x200) eq substr($zeroes,0x200)
					|| (substr($backup,$bin_len-2) eq pack("H*","BEEF") && !$bin_short)
					)
				&& substr($backup,0,0x03) eq substr($master,0,0x03)
				&& substr($backup,0x5A,$MAX_BOOT_SIZE-0x5A) eq substr($master,0x5A,$MAX_BOOT_SIZE-0x5A)
				);
			warn "WARNING: Dropping obsolete (but similiar) backup! Use --uninstall next time.\n";
			}
		sysseek DEVICE,$backup_offset,SEEK_SET or die "Error seeking $device_filename";
		$bin_len==syswrite DEVICE,$master or die "Error backing up the master";
		}
	sysseek DEVICE,0,SEEK_SET or die "Error seeking $device_filename";
	$bin_len==syswrite DEVICE,$bin or die "Error writing new master of BIOSautoRAID";
	}
if ($opt_uninstall) {
	sysseek DEVICE,0,SEEK_SET or die "Error seeking $device_filename";
	$bin_len==syswrite DEVICE,$backup or die "Error writing backup back to the master";
	sysseek DEVICE,$backup_offset,SEEK_SET or die "Error seeking $device_filename";
	$bin_len==syswrite DEVICE,$zeroes or die "Error clearing the backup area";
	}

close DEVICE or die "close \"$device_filename\": $!";

print "OK; ".($opt_install ? ($installed ? "re" : "")."installed" : "uninstalled")."\n";
$all_ok=1;
