#!/usr/bin/perl -w

use IO::Handle;

# -- Things to tweak --
@BUILD_TAGS = ( 'OOO_STABLE_1', 'HEAD' );
$BUILDNAME = 'RH8.0(x86)'; # best if it includes the OS etc.
$MAINTAINER = 'Michael Meeks <michael@ximian.com>';
$BUILD_OS = 'RedHat 8.0';

# -- Things not to tweak --
$TINDER_DEST = 'ooo@ooo.ximian.com';
$SENDMAIL = '/usr/sbin/sendmail';
$LOGDIR = $ENV{'HOME'} . "/build-logs";
`mkdir -p $LOGDIR`;

-X $SENDMAIL || die "No sendmail";

# 'not_running', 'building', 'build_failed', 'test_failed', 'success'
sub start_mail {
	my $status = shift;
	my $tree   = shift;
	my $starttime = shift;
	my $MAIL;
	my $MAIL_HEADER =
		"X-Tinder: cookie\n".
		"\n". # vital header / body separator
		"tinderbox: administrator: michael\@ximian.com\n".
		"tinderbox: builddate: deprecated\n".
		"tinderbox: starttime: $starttime\n".
		"tinderbox: buildname: $BUILDNAME\n".
		"tinderbox: errorparser: unix\n".
		"tinderbox: status: $status\n".
		"tinderbox: timenow: ". time(). "\n".
		"tinderbox: tree: $tree\n".
		"tinderbox: END\n".
		"\n"; # end of tinder header separator

	print "Mailing '$status'\n";

#	open ($MAIL, "|cat > $TINDER_DEST") || die "Can't log to file";
	open ($MAIL, "|$SENDMAIL $TINDER_DEST") || die "Can't send mail";
	print $MAIL $MAIL_HEADER;

	return $MAIL;
}

sub end_mail {
    my $MAIL = shift;
    close ($MAIL);
}

sub send_msg {
    my $status = shift;
    my $tree   = shift;
    my $starttime = shift;
    my $mailbody = shift;

    $MAIL = start_mail ($status, $tree, $starttime);
    local $SIG{PIPE} = 'IGNORE';
    print $MAIL "Tinder build from $MAINTAINER, on $BUILD_OS\n"; 
    print $MAIL $mailbody;
    end_mail ($MAIL);
}

sub build_one {
    my $tree = shift;
    my $starttime = time();
    my $buildlog = "$LOGDIR/log-$tree-$starttime";
    my $ret;
    my $MAIL;

    print "Building $tree: ".$starttime."\n";

    $MAIL = start_mail ('building', $tree, $starttime);
    end_mail ($MAIL);

    my $mailbody = '';

    printf "Building log: $buildlog ...\n";
    if (system ("./build-ooo $tree --checkout >& $buildlog")) {
	$status = 'build_failed';
    } else {
	$status = 'success';
    }

    sleep 1; # time to flush that log.
    
    my $LOG;
    open ($LOG, "$buildlog") || warn "Can't open $buildlog: $!";
    while (<$LOG>) {
	$mailbody .= $_;
    }
    close ($LOG);

    send_msg ($status, $tree, $starttime, $mailbody);
}

if (@ARGV) {
	@BUILD_TAGS = @ARGV;
}

while (1) {
	print "Starting cycle ".gmtime(time())."\n";
	foreach $a (@BUILD_TAGS) {
   		 build_one ($a);
	}
	print "Done cycle, pause ";
	sleep (60 * 5);
}
