# $Id: Command.pm,v 1.1.1.1 2001/06/04 23:39:28 proclus Exp $

package BB::Command;
use strict;

#
# Wrapper arround a shell command
#

use Logger;

sub new {
	my ($proto, $template, $label) = @_;
	my $type = ref($proto) || $proto;
	my $this = bless({}, $type);

	$this->{theTmpl} = $template;
	$this->{theLabel} = $label;
	$this->{theText} = undef;
	$this->{thePid} = undef;
	$this->{isConstant} = 0; # this field is not used

	return $this;
}

sub clone {
	my ($this, $cfg) = @_;

	# my %h = map { $_ => $this->{$_} } 
	my $clone = bless({ %{$this} }, ref($this));

	$clone->configure($cfg);

	return $clone;
}

sub text {
	my ($this, $text) = @_;
	$this->{theText} = $text if defined $text;
	die() unless defined $this->{theText};
	return $this->{theText};
}

sub label {
	my ($this, $label) = @_;
	$this->{theLabel} = $label if defined $label;
	return $this->{theLabel};
}

sub template {
	my ($this, $template) = @_;
	$this->{theTmpl} = $template if defined $template;
	return $this->{theTmpl};
}

sub constant {
	my ($this, $be) = @_;
	$this->{isConstant} = $be if defined $be;
	return $this->{isConstant};
}

sub configure {
	my ($this, $cfg) = @_;

	die() unless defined $this->{theTmpl};
	$this->{theText} = BB::Tools::EvalVars($this->{theText} || $this->{theTmpl}, $cfg);
	$this->{theText} =~ s/\s*\n\s*/ /mg;

	$this->{theLabel} = BB::Tools::EvalVars($this->{theLabel}, $cfg)
		if defined $this->{theLabel};
}

sub read {
	my ($this, $buf, $size) = @_;

	my $lbl = $this->{theLabel} || '?';
	my $pid = $this->{thePid} || -1;

	return &Log("child[$pid] $lbl cannot read cmd output, $!") if !defined $size;

	if ($size > 0) {
		chomp($buf);
		my $pid = $this->{thePid} || -1;
		if ($buf =~ /\n/m) {
			$buf = &ButifyBuf($buf);
			&Log("child[$pid] $lbl got:\n$buf");
		} else {
			&Log("child[$pid] $lbl got: $buf");
		}
	}
}

sub start {
	my ($this, $pid) = @_;

	die() if defined $this->{thePid};
	$this->{thePid} = $pid;
	my $lbl = $this->{theLabel} || '?';
	&Logf("child[$pid] $lbl started: %s", $this->text());
}

sub done {
	my ($this, $exit_code) = @_;

	my $lbl = $this->{theLabel} || '?';
	my $pid = $this->{thePid} || -1;
	&Log("child[$pid] $lbl finished.");
}

1;
