use strict;
use vars qw($loaded @nitems $list $path);

use Getopt::Std;
use Fan::Attrib;
use Fan::Usage;

BEGIN {
	$| = 1;
	print("1..1\n");
}

END {
	print("not ok 1\n") unless $loaded;
}

$loaded = 1;
print("ok 1\n");

# $Fan::Attrib::LOG = 6;
# Fan::Attrib->new(attr_path => '/not/found/in/system');
# exit;

#
# @nitems = (100, 1000, 10000, 100000);
@nitems = (50000);
$list = '-r-xr-xr-x  1 root  bin  7925 Aug 28 15:58 ftpmirror';
$path = '/usr/local/bin/ftpmirror';

#
&alloc(1) or print("not ok 2\n"), exit(1);
print("ok 2\n");
&alloc(0) or print("not ok 3\n"), exit(1);
print("ok 3\n");

# to numeric
for my $n (@nitems) {
	for my $l (1, 0) {
		&run($n, $l);
	}
}

# success terminate
exit;

# show system resource usage
sub get_maxrss {
	my $u = getrusage;
	$u->ru_maxrss;
}

# try once for each type.
sub alloc ($) {
	my $use_list = shift;
	my $a;

	if ($use_list) {
		ref($a = Fan::Attrib->new(attr_list => $list))
			or warn("Can't create Attrib object"), return undef;
	} else {
		ref($a = Fan::Attrib->new(attr_path => $path))
			or warn("Can't create Attrib object"), return undef;
	}
	1;
}

# main processing...
sub run {
	my $num = shift;
	my $use_list = shift;

	#
	my $rss = &get_maxrss;
	print "* before (n=$num, L=$use_list): maxrss=$rss\n";

	# main loop...
	for (my $i = 0; $i < $num; $i++) {
		&alloc($use_list) or die("Can't allocate");
	}

	# after care
	$rss = &get_maxrss;
	print "* result (n=$num, L=$use_list): maxrss=$rss\n";

	# check result.
	if ($rss > 4000) {
		print "* Too large memory used..., ";
#		print "dump vars...\n";
#		require "dumpvar.pl";
#		dumpvar('Fan::Attrib');
#		print "* and, ";
		print "kill myself.\n";
		kill 6, $$;
		sleep(10);
	}

	# success...
	1;
}
