#!/usr/bin/perl -w

use integer;
use Getopt::Std;
use strict;
use threads;
use IO::Seekable;

sub run_dir_wr($);

# SUPPORTED OPTIONS.
my $path_opt = 'p';
my $num_opt  = 'n'; # Number of processes
my $task_opt = 't';

my %options;

getopts ("${path_opt}:${num_opt}:${task_opt}:", \%options)
	or die "getopts() failed: $!.";

die "Path wasn't specified (-$path_opt option)\n"
unless $options{$path_opt};

my $num = $options{$num_opt} ? $options{$num_opt} : 1;

if (!$options{$task_opt}) {
	for (my $i = 0; $i < $num; $i++) {
		my $thr;
		$thr = threads->new(\&run_dir_wr, "d" . ($i));
	}
	<STDIN>;
} elsif ($options{$task_opt} == '1') {
	run_file_wr('f0');
} elsif ($options{$task_opt} == '2') {
	run_dir_wr('d0');
} else {
	die "Wrong -$task_opt value\n";
}

sub form_str($$)
{
	my $ret;
	my $chr = $_[1];
	my $tmp = 0;
	
	for (my $i = 0; $i < $_[0]; $i++) {
		$ret = $ret . chr int rand 256;
		$tmp ++;
	}

	return $ret;
}

sub run_dir_wr($)
{
	print "Direntries write: $options{$path_opt}/$_[0]\n";
	die "Can't create directory $options{$path_opt}/$_[0]/\n" unless mkdir "$options{$path_opt}/$_[0]/";

	my $fcnt = 0;
	my $dcnt = 0;
	my $chcnt = 0;
	my $blkcnt = 0;
	my $fifocnt = 0;
	
	while (1) {
		my $rnd = rand 100;
		
		if ($rnd < 70) {
			my $rnd = rand 100;

			if ($rnd < 40) {
				open FF, ">$options{$path_opt}/$_[0]/f$fcnt";
				close FF;
				$fcnt += 1;
			} elsif ($rnd < 80) {
				mkdir "$options{$path_opt}/$_[0]/d$dcnt";
				$dcnt += 1;
			} elsif ($rnd < 87) {
				`mknod $options{$path_opt}/$_[0]/ch$chcnt c 0 0`;
				$chcnt += 1;
			} elsif ($rnd < 93) {
				`mknod $options{$path_opt}/$_[0]/blk$blkcnt b 0 0`;
				$blkcnt += 1;
			} else {
				`mknod $options{$path_opt}/$_[0]/fifo$fifocnt b 0 0`;
				$fifocnt += 1;
			}
		} else {
			my $rnd = rand 100;
			if ($rnd < 40) {
				my $n = int rand $fcnt + 1;
				`rm -rf $options{$path_opt}/$_[0]/f$fcnt`;
			} elsif ($rnd < 80) {
				my $n = int rand $dcnt + 1;
				`rm -rf $options{$path_opt}/$_[0]/d$dcnt`;
			} elsif ($rnd < 87) {
				my $n = int rand $chcnt + 1;
				`rm -rf $options{$path_opt}/$_[0]/ch$chcnt`;
			} elsif ($rnd < 93) {
				my $n = int rand $blkcnt + 1;
				`rm -rf $options{$path_opt}/$_[0]/blk$blkcnt`;
			} else {
				my $n = int rand $fifocnt + 1;
				`rm -rf $options{$path_opt}/$_[0]/fifo$fifocnt`;
			}
		}
	}
}

