#

sub printdate () {
    print scalar(localtime),"\n";
}

sub setstatus ($) {
    open S, ">this-status.new" or die $!;
    print S $_[0],"\n" or die $!;
    close S or die $!;
    rename "this-status.new","this-status" or die $!;
}

sub startprocess ($$$) {
    my ($i,$o,$c) = @_;
    print LOG "  $c\n" or die $!;
    print "  $c\n" or die $!;
    defined($p= fork) or die $!;
    if ($p) { $processes{$p}= $c; return; }
    open STDIN,"$i" or die "$c stdin $i: $!";
    open STDOUT,"$o" or die "$c stdout $o: $!";
    &closepipes;
    exec $c; die "$c: $!";
}

sub endprocesses () {
    while (keys %processes) {
	$p= waitpid(-1,0) or die "wait: $!";
	if (!exists $processes{$p}) { warn "unknown pid exited: $p, code $?\n"; next; }
	$c= $processes{$p};
	delete $processes{$p};
	$? && die "error: command gave code $?: $c\n";
    }
    print LOG "  ok\n" or die $!;
    print "  ok\n" or die $!;
}

sub killprocesses {
    for $p (keys %processes) {
	kill 15,$p or warn "kill process $p: $!";
    }
    undef %processes;
}

sub readfsys ($) {
    my ($fsnm) = @_;
    open F, "$etc/fsys.$fsnm" or die "Filesystems $fsnm unknown ($!).\n";
    for (;;) {
	$_= <F> or die; chomp; s/\s*$//;
	last if m/^end$/;
	next unless m/\S/;
	next if m/^\#/;
	if (m/^prefix\s+(\w+)\s+(\S.*\S)$/) {
	    $prefix{$1}= $2;
	    next;
	} elsif (m/^prefix\-df\s+(\w+)\s+(\S.*\S)$/) {
	    $prefixdf{$1}= $2;
	    next;
	}
	push @fsys,$_;
    }
    close F or die $!;
}

sub parsefsys () {
    if ($tf =~ m,^(/\S*)\s+(\w+)$,) {
	$atf= $1;
	$tm= $2;
	$prefix= '<local>';
	stat $atf or die "stat $atf: $!";
	-d _ or die "not a dir: $atf";
	$rstr= '';
    } elsif ($tf =~ m,^(/\S*)\s+(\w+)\s+(\w+)$,) {
	$atf= $1;
	$tm= $2;
	$prefix= $3;
	defined($prefix{$prefix}) or die "prefix $prefix in $tf ?\n";
	$rstr= $prefix{$prefix}.' ';
    }
}

sub openlog () {
    unlink 'log';
    $u= umask(007);
    open LOG, ">log" or die $!;
    umask $u;
    select(LOG); $|=1; select(STDOUT);
}

$SIG{'__DIE__'}= 'killprocesses';

1;
