#!/s/std/bin/perl

package Crasherase;

use strict;

# change if we use a different SATA card.  Right now this is what is in egon
my $MODULE = "sata_promise";

sub load_module {
	`modprobe $MODULE`;
}

sub remove_module {
	`rmmod $MODULE`;
}

sub get_device_info {
	my $devline = `dmesg|tail -10`;
	$devline =~ /SCSI device (sd.): (\d+)/;
	my $realdev = "/dev/$1";
	my $num_secs = $2;
	return ($realdev, $num_secs);
}

sub write_block {
	my ($device, $seek, $count, $blocksize) = @_;
	# /dev/urandom is too damn slow, only giving us 2MB/sec.  Blaaaargh
	# need to use /dev/zero.
	my $com = 'dd if=/dev/zero of=' . $device . ' seek=' . $seek . ' count=' . $count . ' bs=' . $blocksize . 'k > /dev/null 2> /dev/null';
	`$com`;
}

sub get_device {
	# find the device ids of any usb storage devices
	my $scsi_dir = "/proc/scsi/usb-storage";
	my @scsi_ids = <$scsi_dir/*>;
	foreach (@scsi_ids) {
		$_ =~ s/.*\///g;
	}
	# get a list of all scsi devices
	my @scsi_devs = `sg_map -i -x`;
	my @final_device;
	my $final_dev_count = 0;	# if this becomes more than 1, then we have
								# too many USB disks!
	# find the correct device mapping
	foreach (@scsi_devs) {
		my @vals = split;
		foreach (@scsi_ids) {
			if ($vals[1] eq $_) {
				# we found a device!
				push @final_device, @vals;
				$final_dev_count++;
			}
		}
	}
	# ok we should have our device now
	die "Too many USB disks were found, please remove extra disks and try again\n" if ($final_dev_count > 1);
	
	# return the dev in an array so we can get the proper elements
	# important elements: $final_device[6] is the block device (e.g. /dev/sdb)
	# $final_device[7] and [8] are the manufacturer and device type

	return @final_device;
}

sub get_disk_size {
	my ($dev) = @_;
	my @result;
	my @str = `sg_readcap -b $dev`;
	$_ = $str[0];
	my @data = split;
	my $num_secs = hex($data[0]);
	my $sec_size = hex($data[1]);

	push @result, $num_secs;
	push @result, $sec_size;

	# result[0] is number of sectors, $result[1] is sector size
	return @result;
}


1;
