#! /usr/bin/perl
# anders@fupp.net 2009-09-03
# Check if we can read and write to disk!!!

use Getopt::Std;
getopts('f:');

$magictxt = "%%OIOIMAGISK%%";
$log = "/var/tmp/disk_write.log";
$time = localtime(time);

sub err {
	my $txt = shift;
	my $ret = shift;
	print "$txt\n";
	if ($ret) {
		exit($ret);
	} else {
		open(LOG, ">>$log");
		print LOG "$txt [$time]\n";
		close(LOG);
		exit(2);
	}
}

if (!$opt_f) {
	err("Usage: -f <file to write/read>", 3);
}

if (-e $opt_f) {
	err("File $opt_f already exists. Cannot check.", 3);
}

# Write the file
if (open(FILE, ">$opt_f")) {
	if (!print FILE "$magictxt\n") {
		close(FILE);
		err("Could not write content to $opt_f: $!");
	}
	if (!close(FILE)) {
		err("Could not close $opt_f after writing: $!");
	}
} else {
	err("Could not open $opt_f for writing: $!");
}

# Read the file

if (open(FILE, $opt_f)) {
	$line = <FILE>;
	chomp($line);
	if ($line ne "$magictxt") {
		err("File $opt_f does not have the magic text $magictxt. Something is fishy. Found instead: $line:");
	}
	if (!close(FILE)) {
		err("Could not close $opt_f after reading: $!");
	}
} else {
	err("Could not open $opt_f for reading: $!");
}

if (!unlink($opt_f)) {
	err("Could not delete file $opt_f: $!");
}

print("File $opt_f written, read and deleted OK.\n");
exit(0);
