#!/usr/bin/perl -w

use IO::Handle;

@BUILD_TAGS = ( 'OOO_1_0_2' );

# $BUILDNAME = `hostname`; chomp($BUILDNAME);
$BUILDNAME = 'MyBuild x86';
$TINDER_DEST = 'ooo@ooo.ximian.com';
$SENDMAIL = '/usr/sbin/sendmail';
$LOGDIR = $ENV{'HOME'} . "/build-logs";
`mkdir -p $LOGDIR`;

# '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";

	if ($tree eq 'OOO_STABLE_1') { # secret stuff ...
	    open ($MAIL, ">/dev/null");
	} else {
#	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 $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);

    printf "Building log: $buildlog ...\n";
    if (system ("./build-ooo $tree --checkout >& $buildlog")) {
	$status = 'build_failed';
    } elsif (system ("./package-ooo $tree --clean >> $buildlog 2>&1")) {
	$status = 'test_failed';
    } else {
	$status = 'success';
    }
    
    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);
}
