#! /usr/bin/perl -w
#
# A local client script to send commands to the distribute daemon.
#
# GPL. Copyright 1998 by Christopher Neufeld
#
# If there are no arguments, or only one argument, "-c", exits quietly.
#

use IO::Socket;


exit 0 if $#ARGV == -1 || ( $#ARGV == 0 && $ARGV[0] eq "-c" ) ;

if ( $ARGV[0] eq "-c" ) {   # Drop the '-c' if present.
    shift @ARGV ;
}


# We can remote any command except a "make" or one which writes to a
# file on stdout (because of possible race conditions involving multiple
# NFS appends to a single file).

$canremote = ( $ARGV[0] !~ m/make\s/ && $ARGV[0] !~ m/>>?/ ) ;

if ( ! $canremote ) {
    exec "/bin/sh", "-c", $ARGV[0] ;
    die "Returned from exec!\n";
}



chomp($cwd = `pwd` );

$home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
    (getpwuid($<))[7] || die "You're homeless!\n";

$localsockpathdir = "$home/.distribute";
$localsockfname = "distribute";
$localsockpathname = $localsockpathdir . "/" . $localsockfname ;

die "Can't find my socket.\n" if ! -S $localsockpathname;

# Connect to the server. If it's not accepting any further connections
# at this time, loop until the socket becomes available.
do {
    $server = IO::Socket::UNIX->new( Type   => SOCK_STREAM,
				     Peer   => "$localsockpathname",
				   ) ;
} until $server;

$server->autoflush(1);

$command = join(' ', @ARGV);

# Put in the chdir to the current working directory.
$command = "cd $cwd; " . $command;

print $server $command, "\n";

$retcode = 0;

while (<$server>) {
    next if m/^OUTPUT [0-9]*$/ ;
    
    if ( m/^DONE ([0-9]*)$/ ) {
	$retcode = $1;
	last;
    }

    if ( m/^# / ) {
	s/^# //g ;    # strip the protecting '# ' string
	print ;
    }
}

exit $retcode;
