#!/home/jc0/aix/bin/perl
#
# nullfile [opts] [file]...
# nullfile [opts] <filelist
#
# Test the files for (initial) null bytes.  This is to  track  down  a
# problem  on  AIX  that  seems  to  be replacing files' contents with
# nulls.  The first $cnt bytes are read, and if they are null, a  "Bad
# file"  message  is produced.  An empty file produces an "Empty file"
# message.  There are also complaints about unreadable files.
#
# Options:
#
# +c  Show   files with null contents (default).
# -c  Ignore files with null contents.
#
# +d  Show   debug output.
# -d  Ignore debug output (default).
#
# +e  Show   empty files.
# -e  Ignore empty files (default).
#
# +p  Show   files with permission problems
# -p  Ignore files with permission problems (default)..

$| = 1;
$stat = 0;	# Exit status.
$cnt = 2000;	# Number of bytes to read from each file.
$cfl = 1;	# Test for null contents.
$dfl = $dbg = 0;
$efl = 0;	# Test for empty files.
$pfl = 0;	# Tell about permission problems.

for $f (@ARGV) {
	if (($fl,$opt,$arg) = ($f =~ /^([-+])([cedp\d])(.*)/i)) {
		if ($opt =~ /c/i) {
			$cfl = ($fl eq '+') ? 1 : 0;
		} elsif ($opt =~ /d/i) {
			$dfl = $dbg = $arg || 1;
		} elsif ($opt =~ /e/i) {
			$efl = ($fl eq '+') ? 1 : 0;
		} elsif ($opt =~ /p/i) {
			$pfl = ($fl eq '+') ? 1 : 0;
		} elsif ($f =~ /^([-+])(\d+)/) {
			$cnt = int($2);
		} else {
			print STDERR "$0: Option \"$f\" unknown.\n";
		}
	} else {
		&checkfile($f);
	}
}
if (!$files) {
	for $l (<STDIN>) {
		for $f (split(/\s+/,$l)) {
			if ($f) {
				&checkfile($f);
			}
		}
	}
}
exit $stat;

sub checkfile {
	local($f) = @_;
	++$files;
	if (open(F,"<$f")) {
		if ($n = read(F,$x,$cnt)) {
			$x =~ s/\0//g;
			if (!$x) {
				print "Bad file \"$f\" (first $cnt bytes are null)\n" if $cfl;
				++$stat;
			}
		} elsif ($n < 0) {
			print "Can't read \"$f\" [$!]\n" if $pfl;
		} else {
			print "Empty file \"$f\"\n" if $efl;
		}
	} else {
		print "Can't open \"$f\" [$!]\n" if $pfl;
	}
}
