#!/usr/bin/perl

use strict;
use English;

my $ksrc        = "/data/home/roland/Src/linux-2.6.9";
my $kbuild_base = "/data/home/roland/Src/kbuild-";
my $parallel    = 6;

sub xpath ($) {
  my $arch = shift;

  return "/usr/local/crosstool/$arch/$arch-unknown-linux-gnu/gcc-3.4.1-glibc-2.3.2/bin/$arch-unknown-linux-gnu-";
}

my @targets = (
	       {
		arch => "i386",
		cross_compile => ""
	       },
	       {
		arch => "x86_64",
		cross_compile => xpath("x86_64")
	       },
 	       {
 		arch => "ppc64",
 		cross_compile => "/usr/local/crosstool/ppc64/powerpc64-unknown-linux-gnu/gcc-3.4.1-glibc-2.3.2/bin/powerpc64-unknown-linux-gnu-",
 		cross32_compile => "/usr/local/crosstool/ppc32/powerpc-750-linux-gnu/gcc-3.4.1-glibc-2.3.2/bin/powerpc-750-linux-gnu-"
 	       },
 	       {
 		arch => "ia64",
 		cross_compile => xpath("ia64")
 	       },
 	       {
 		arch => "sparc64",
 		cross_compile => xpath("sparc64")
 	       },
	       {
		arch => "i386",
		cross_compile => "",
		cc => "gcc-2.95"
	       },
 	       {
 		arch => "ppc",
 		cross_compile => "/usr/local/crosstool/ppc32-440/powerpc-440-linux-gnu/gcc-3.4.1-glibc-2.3.2/bin/powerpc-440-linux-gnu-"
 	       },
	      );

chdir $ksrc or die "Couldn't chdir to $ksrc";

for my $a (@targets) {
  my $destdir = $kbuild_base . $a->{arch};
  $destdir .= "-$a->{cc}" if ($a->{cc});

  my $env = "ARCH=$a->{arch} CROSS_COMPILE=$a->{cross_compile}";
  $env .= " CROSS32_COMPILE=$a->{cross32_compile}" if ($a->{cross32_compile});
  $env .= " CC=$a->{cc}" if ($a->{cc});

  print "compiling for $a->{arch} ";
  print "($a->{cc}) " if ($a->{cc});
  print "... ";

  my $output = `$env make -j$parallel O=$destdir 2>&1`;

  if ($CHILD_ERROR) {
    print "FAILED\n";
  } else {
    print "success\n";
  }

  my $errs = 0;
  for my $line (split /\n/, $output) {
    if ($line =~ /error:|warning:/i) {
      print "    $line\n";
      ++$errs;
    }
  }

  if ($errs) {
    print "\n";
  }
}
