#!/usr/bin/perl
#
#  emchain -- toolchain builder for cross compiling
#  Copyright (C) 2006-2008, 2010  Neil Williams <codehelp@debian.org>
#  Copyright (c) 2007 Simon Richter <sjr@debian.org>
#
#  This package is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

use Cwd;
use File::HomeDir;
use File::Basename;
use Text::Wrap;
use Config::Auto;
use Debian::DpkgCross;
use Term::ANSIColor qw(:constants);
use Text::Balanced qw(extract_bracketed);
use strict;
use warnings;
use vars qw/ $verbose $dpkg_cross_dir $suite $arch $line $aptcmd
$skip_gcc $skip_binutils $skip_libc $host $gcc_latest $gcc_vers
$gcc_pkg_v $binutils_vers $libc_latest $libc_vers $libc_pkg_v
$binutils_dir $gcc_dir $dev $binutils_deb @glibc_list @glibc_list2
@glibc_list3 $check $glibc_count $home $ourversion $progname $logfile
$date $log $cmdline $status $environ $result $workdir $msg $ignore
*OLDOUT *OLDERR $forcing $arglog $logdir $uclibc $uclibc_vers
$binutils_cross $binutils_pkg $target_gnu_type /;

$ourversion = &tools_version();
$progname = basename($0);
$verbose = 1;
$forcing = 0;
$libc_latest = "6";
# read in dpkg-cross default arch
&read_config();
$arch = &get_architecture();
$target_gnu_type = &check_arch ($arch);
$suite = "unstable";
$logdir = cwd;
$date = `date +%F`;
chomp ($date);

## Pseudo-code:
# $ apt-get source gcc-3.4 binutils libc
# $ cd binutils-2.17
# $ TARGET=$target_gnu_type fakeroot debian/rules binary-cross (replace arch by arm, alpha,...)
# dpkg -i built-package
# apt-cross -i libdb1-compat libc6 libc6-dev linux-kernel-headers
# $ export GCC_TARGET=$arch
# $ export DEB_CROSS_INDEPENDENT=yes (for gcc-4.1 and later).
# $ cd gcc-3.4-3.4.2
# $ debian/rules control
# $ dpkg-buildpackage -b -rfakeroot

sub usageversion {
	print(STDERR <<END)
emchain version $ourversion

emchain is deprecated.

Usage:
 emchain [-a|--arch ARCH] [-l|--log] [-v|--verbose] [-q|--quiet]
 emchain [-a|--arch ARCH] [-l|--log] [-v|--verbose] [-q|--quiet] -f|--force
 emchain [-a|--arch ARCH] [-l|--log] [-v|--verbose] [-q|--quiet] -u|--uclibc
 emchain [-a|--arch ARCH] [-l|--log] [-v|--verbose] [-q|--quiet] -i|--ignore
 emchain -?|-h|--help|--version

Commands:
 -f|--force:          continue the build even if the upstream native build has failed.
 -i|--ignore:         ignore the installed toolchain and build another one.
 -u|--uclibc:         attempt to create a uClibc toolchain link from the existing
                       gcc/eglibc toolchain. (Experimental!)

Options:
 -a|--arch ARCH:      set architecture (default: defined by dpkg-cross).
 -s|--suite SUITE:    set the suite to match
 -l|--log:            write a logfile in the current directory.
 -v|--verbose:        be verbose (repeat for more verbosity).
 -q|--quiet:          be quiet [default]
 -?|-h|--help:        print this usage message and exit
 --version:           print this usage message and exit

emchain implements the EmdebianSlind toolchain build process for
the default versions of gcc, binutils and libc. To build toolchains
for older compilers, see the Emdebian website: www.emdebian.org

emchain uses gcc-defaults to determine the default
versions of toolchain packages, downloads the source for each missing
package, builds the package using EmdebianSlind options and commands,
installs the cross-built packages and toolchain packages.

END
		|| die "$progname: failed to write usage: $!\n";
}

$arglog = 0;
while( @ARGV ) {
	$_= shift( @ARGV );
	last if m/^--$/;
	if (!/^-/) {
		unshift(@ARGV,$_);
		last;
	}
	elsif (/^(-\?|-h|--help|--version)$/) {
		&usageversion();
		exit( 0 );
	}
	elsif (/^(-v|--verbose)$/) {
		$verbose++;
	}
	elsif (/^(-q|--quiet)$/) {
		$verbose--;
	}
	elsif (/^(-a|--arch)$/) {
		$arch = shift(@ARGV);
	}
	elsif (/^(-l|--log)$/) {
		$arglog = 1;
	}
	elsif (/^(-s|--suite)$/) {
		$suite = shift;
	}
	elsif (/^(-f|--force)$/) {
		$forcing = 1;
	}
	elsif (/^(-u|--uclibc)$/) {
		$uclibc = 1;
	}
	elsif (/^(-i|--ignore)$/) {
		$ignore = 1;
	}
}

$msg = "$progname: no default architecture found.\n";
$msg .= "Please use '$progname --arch ARCH'.\n";
die $msg if ((!$arch)||($arch eq ""));
my $target_gnu_type = &check_arch($arch);
$logfile = "emchain-" . $arch . "-" . $date . ".log" if ($arglog == 1);
if (defined $logfile and -f $logfile and $arglog == 1)
{
	my $time = `date +%H-%M`;
	chomp ($time);
	$logfile = "emchain-" . $arch . "-" . $date . "-" . $time . ".log"
}

if (not defined $uclibc)
{
	my $hostcheck = &host_arch;
	if (($arch eq $hostcheck) or (($arch eq "i386") and ($hostcheck eq "amd64")) or
	(($arch eq "amd64") and ($hostcheck eq "i386")))
	{
		print GREEN, wrap('','', "The requested cross building architecture ",
		"($arch) does not need a toolchain to build on host ($hostcheck)! ",
		"Nothing to do. See emsetup (1).\n"), RESET, "\n";
		exit(0);
	}
}

if ($verbose >= 2)
{
	print CYAN, "Building toolchain in '" . cwd . "'\n", RESET;
	print CYAN, "Options used:\n", RESET;
	print CYAN, "verbose=$verbose\n", RESET;
	print GREEN, "forcing=YES\n", RESET if ($forcing != 0);
	(defined $logfile) ? print CYAN, "logging to $logfile\n", RESET :
		print CYAN, "not logging output.\n", RESET;
}
if (!&check_arch($arch)){
	$msg = (qq;Error: dpkg-cross does not currently support "$arch".;);
	die RED, "\n$msg", RESET, "\n";
}

if ($logfile)
{
	open OLDOUT, ">&STDOUT" or die "cannot duplicate stdout: $!\n";
	open OLDERR, ">&STDERR" or die "cannot duplicate stderr: $!\n";
	open BUILD, "| tee $logfile" or die "could not open pipe to tee $logfile: $!";
	close STDOUT;
	close STDERR;
	open STDOUT, ">&BUILD" or die "cannot reopen stdout: $!";
	open STDERR, ">&BUILD" or die "cannot reopen stderr: $!";
	print "emchain $ourversion build log.\t$date\tArchitecture: $arch\n\n";
}

# prepare variable names.
$skip_gcc = 0;
$skip_binutils = 0;
$skip_libc = 0;
$host = &host_arch;
$gcc_latest = "4.3";
$gcc_vers = "gcc";
$libc_vers = "libc${libc_latest}";
use Data::Dumper;
my @madison = `rmadison -s $suite --architecture $host $gcc_vers`;
#print Dumper (@madison);
for my $vers (@madison)
{
	if ($vers =~ /^ +$gcc_vers ?\| +[0-9]:([0-9]\.[0-9]).+ ?\| +$suite ?\| ?$host$/) {
		$gcc_latest =$1;
	}
}
$gcc_vers .= "-" . $gcc_latest;
@madison = `rmadison -s $suite --architecture $host libc6 binutils $gcc_vers`;
#print Dumper (@madison);
for my $vers (@madison)
{
	if ($vers =~ /^ +libc6 ?\| +(.*) ?\| +$suite ?\| ?$host$/) {
		$libc_pkg_v = $1;
	}
	if ($vers =~ /^ +binutils ?\| +(.*) ?\| +$suite ?\| ?$host$/) {
		$binutils_vers = $1;
		$binutils_dir = &split_debian($binutils_vers);
	}
	if ($vers =~ /^ +$gcc_vers ?\| +(.+) ?\| +$suite ?\| ?$host$/) {
		$gcc_pkg_v = $1;
		$gcc_dir = &split_debian ($gcc_pkg_v);
	}
}
if (not defined $binutils_vers)
{
	my $msg = "\nERROR: 'rmadison -s $suite --architecture $host binutils' failed!\n";
	$msg .= "Did you specify a codename (lenny) instead of a suite (stable)?\n";
	$msg .= "(rmadison only supports codenames).";
	die (RED, $msg, RESET, "\n\n");
}
my $gcc_src="";

if (defined $uclibc)
{
	&uclibc_build_chain;
	exit (0);
}
elsif (not defined $ignore)
{
	my $check = &check_toolchains ($arch, $target_gnu_type);
	$msg = "$progname: You already have a usable toolchain installed ";
	$msg .= "for $arch on $suite using eglibc. Use '$progname -a $arch --ignore' ";
	$msg .= " if you want to build the toolchain again or ";
	$msg .= "'$progname -a $arch --uclibc' if you want the uClibc extension.\n";
	if ($check eq "true")
	{
		my $list =  &prepare_checklist($arch, $target_gnu_type);
		my $str = join (" ", @$list);
		system ("dpkg -l $str");
		warn RED, wrap('','',"\n$msg"), RESET, "\n";
		exit (1);
	} else {
		my $list =  &prepare_checklist($arch, $target_gnu_type);
		my $str = join (" ", @$list);
		system ("dpkg -l $str");
	}
}

$dev = $libc_vers . "-dev";
$binutils_deb = "binutils-${target_gnu_type}_${binutils_vers}_${host}.deb";
@glibc_list=qw//;
@glibc_list2=qw//;
@glibc_list3=qw//;
$glibc_count = 0;
&check_source_version("binutils");
&check_source_version("linux-kernel-headers");
&check_source_version($libc_vers);
&check_source_version($gcc_vers);

$log = "\nThis is emchain $ourversion.\n Toolchain builder for cross compiling.\n\n";
print CYAN, $log, RESET if ($verbose >= 3);
$log = "Using : \n";
# catch errors where package-version does not match the unpacked directory name.
if(! -d "$gcc_dir")
{
	opendir(DIR, ".") or die ("Cannot open current directory: $!");
	my @dirs=readdir(DIR);
	closedir(DIR);
	foreach my $f (@dirs)
	{
		if ((-d $f) && ($f =~ /^$gcc_dir.*/) && (-d "$f/debian"))
		{
			$gcc_dir = $f;
		}
	}
}
$log .= "$gcc_vers ($gcc_pkg_v) in $gcc_dir/\n";
$log .= "binutils $binutils_vers in binutils-$binutils_dir/\n";
$log .= "$libc_vers v$libc_pkg_v\n";
print CYAN, $log, RESET if ($verbose >= 2);

# apt-get source will skip existing downloads if up to date.
$log = "Running apt-get source . . . \n";
print GREEN, $log, RESET if ($verbose >= 2);
if ($verbose < 2) { $aptcmd = "apt-get -q"; }
else { $aptcmd = "apt-get"; }

$log = "$aptcmd source $gcc_vers=$gcc_src binutils=$binutils_vers eglibc=$libc_pkg_v";
print CYAN, "$log\n", RESET if ($verbose >= 2);
my $exitval = system "$log";
# catch all in case there was an unknown error.
exit($exitval) if ($exitval != 0);

print GREEN, "Running sudo - enter your sudo password if prompted.\n", RESET;

if (! -f $binutils_deb) {
	my $dir = $binutils_dir;
	my $cwd = cwd;
	chdir ($dir);
	&check_emdebian_control();
	print CYAN, "Building $binutils_deb in $cwd/$dir\n", RESET if ($verbose >= 2);
	system ("TARGET=$arch fakeroot debian/rules binary-cross");
	chdir ("../");
	system ("sudo dpkg -i $binutils_deb") if ($forcing == 0);
}
system ("apt-cross -a $arch -v -u");
# apt-cross also skips download/conversion of existing debs
# but does not skip installation. :-(
if ($verbose < 2) { $aptcmd = "apt-cross -i"; }
else { $aptcmd = "apt-cross -v -i"; }
# check with dpkg-cross --status for Status: install ok installed\n
$cmdline = &check_cross("libdb1-compat");
$cmdline .= &check_cross("$libc_vers");
$cmdline .= &check_cross("$dev");
$cmdline .= &check_cross("linux-kernel-headers");
# only run cmdline if there is something for apt-cross to do
if (($cmdline ne "") && ($forcing == 0))
{
	system("sudo $aptcmd -a $arch $cmdline");
}
$log = "";

push @glibc_list, "gcc-${gcc_latest}-${target_gnu_type}-base_${gcc_pkg_v}_${host}.deb";
push @glibc_list, "libstdc++${libc_latest}-${arch}-cross_${gcc_pkg_v}_all.deb";
push @glibc_list, "gcc-${gcc_latest}-${target_gnu_type}_${gcc_pkg_v}_${host}.deb";
push @glibc_list, "cpp-${gcc_latest}-${target_gnu_type}_${gcc_pkg_v}_${host}.deb";
push @glibc_list, "libgcc1-${arch}-cross_${gcc_pkg_v}_all.deb";
$glibc_count += scalar @glibc_list;

foreach $check (@glibc_list) {
	$log = "checking for $check\n";
	print CYAN, $log, RESET if ($verbose >= 3);
	if (-f $check) {
		$skip_gcc++;
	}
	else {
		$log = "missing $check\n";
		print CYAN, $log, RESET if ($verbose >= 2);
	}
}

push @glibc_list2, "g++-${gcc_latest}-${target_gnu_type}_${gcc_pkg_v}_${host}.deb";
push @glibc_list2,
	"libstdc++${libc_latest}-${gcc_latest}-dev-${arch}-cross_${gcc_pkg_v}_all.deb";

$glibc_count += scalar @glibc_list2;
foreach $check (@glibc_list2) {
	$log = "checking for $check\n";
	print CYAN, $log, RESET if ($verbose >= 3);
	if (-f $check) {
		$skip_gcc++;
	}
	else {
		$log = "missing $check\n";
		print CYAN, $log, RESET if ($verbose >= 2);
	}
}

push @glibc_list3,
	"libstdc++${libc_latest}-${gcc_latest}-pic-${arch}-cross_${gcc_pkg_v}_all.deb";
push @glibc_list3,
	"libstdc++${libc_latest}-${gcc_latest}-dbg-${arch}-cross_${gcc_pkg_v}_all.deb";

$glibc_count += scalar @glibc_list3;
foreach $check (@glibc_list3) {
	$log = "checking for $check\n";
	print CYAN, $log, RESET if ($verbose >= 3);
	if (-f $check) {
		$skip_gcc++;
	}
	else {
		$log = "missing $check\n";
		print CYAN, $log, RESET if ($verbose >= 2);
	}
}

if ($skip_gcc < $glibc_count) {
	die ("Cannot find $gcc_dir\n") if ( not -d "$gcc_dir");
	chdir ($gcc_dir);
	$environ = "GCC_TARGET=$arch DEB_CROSS=yes";
	system ("$environ debian/rules control");
	# Drop depends on gcc-*-TRIPLET-base
	open (CTRL, "debian/control") or die ("Cannot read debian/control!: $!\n");
	my @ctrl=<CTRL>;
	close (CTRL);
	my @out=();
	foreach my $deps (@ctrl)
	{
		$deps =~ s/gcc-${gcc_latest}-${target_gnu_type}-base \(= \${gcc:Version}\),//g;
		push @out, $deps;
	}
	open (CTRL, ">debian/control") or die ("Cannot write debian/control!: $!\n");
	print CTRL @out;
	close (CTRL);
	$log = "Building gcc in $gcc_dir . . . (this will take a while)\n";
	print GREEN, $log, RESET if ($verbose >= 2);
	$result = 0;
	$result = system "$environ dpkg-buildpackage -b -uc -us -rfakeroot";
	if ($result != 0) {
		print RED, "$progname: Build failed.", RESET;
		($logfile) ? print GREEN, " See $logdir/$logfile for more info.\n", RESET : print "\n";
		if ($logfile)
		{
			close STDOUT;
			close STDERR;
			close BUILD;
			open STDOUT, ">&OLDOUT";
			open STDERR, ">&OLDERR";
		}
		die ("\n");
	}
	chdir ("../");
	foreach $result (@glibc_list)
	{
		$log = "$progname: Failed to create $result package\n";
		if (! -r $result)
		{
			if ($logfile)
			{
				close STDOUT;
				close STDERR;
				close BUILD;
				open STDOUT, ">&OLDOUT";
				open STDERR, ">&OLDERR";
			}
			die ($log);
		}
	}
	foreach $result (@glibc_list2)
	{
		$log = "$progname: Failed to create $result package\n";
		if (! -r $result)
		{
			if ($logfile)
			{
				close STDOUT;
				close STDERR;
				close BUILD;
				open STDOUT, ">&OLDOUT";
				open STDERR, ">&OLDERR";
			}
			die ($log);
		}
	}
	foreach $result (@glibc_list3)
	{
		$log = "$progname: Failed to create $result package\n";
		if (! -r $result)
		{
			if ($logfile)
			{
				close STDOUT;
				close STDERR;
				close BUILD;
				open STDOUT, ">&OLDOUT";
				open STDERR, ">&OLDERR";
			}
			die ($log);
		}
	}
	$log = "$gcc_vers ($gcc_pkg_v) built successfully.\n";
	print GREEN, $log, RESET if ($verbose >= 2);
	print CYAN, "Packages built when using --force are not installed automatically.", RESET if ($forcing == 1);
	if ($forcing == 0)
	{
		my $install = (join (' ', @glibc_list));
		$log = `sudo dpkg -i $install`;
		print $log if ($verbose >= 3);
		$install = (join (' ', @glibc_list2));
		$log = `sudo dpkg -i $install`;
		print $log if ($verbose >= 3);
		$install = (join (' ', @glibc_list3));
		$log = `sudo dpkg -i $install`;
		print $log if ($verbose >= 3);
	}
}
if ($logfile)
{
	close STDOUT;
	close STDERR;
	close BUILD;
	open STDOUT, ">&OLDOUT";
	open STDERR, ">&OLDERR";
}

# end : show confirmation.
die ("Force used! Toolchain might not be usable!\n") if ($forcing == 1);
print GREEN, "\nSuccess! \nInstalled toolchains:\n\n", RESET;
my $all_vers = $gcc_vers;
$all_vers =~ s/gcc/'\?\?\?'/;
$all_vers .= "* 'libstdc*' 'libc6*' 'libgcc1*' 'linux-kernel-headers*'";
my $success = `dpkg -l 'binutils*' $all_vers`;
my @s = split (/\n/, $success);
foreach my $s (@s)
{
	if ($s =~ /^ii +(.*)/)
	{
		print "$1\n";
	}
}
print "\n";
exit 0;

# subroutines.
sub check_cross
{
	# needs a versioned check!
	# TODO the format has changed!
	$log = "checking dpkg-cross status for $_[0] on $arch . . . ";
	$status = `apt-cross -a $arch -s $_[0]`;
	if ((!$status =~ /Status: install ok installed\n/g) || (!$status))
	{
		$log .= "\n$_[0] cross-build not installed yet. Installing ...\n";
		print $log if ($verbose >= 2);
		return "$_[0] ";
	}
	else {
		$log .= "installed ok.\n$status";
	}
	print $log if ($verbose >= 2);
	return "";
}

sub split_debian
{
	return "" if (!$_[0]);
	$_[0] =~ /([0-9\.a-z]*)-[0-9].*/;
	return $1;
}

sub cache_version
{
	my $result;
	if ($forcing == 0)
	{
		$result = &binlookup($_[0]);
		return $result->{VerStr};
	}
	else
	{
		$result = `apt-cache show $_[0] 2>/dev/null`;
	}
	$result =~ /Version: (.*)/g;
	return $1;
}

sub check_source_version
{
	# check the SOURCE version of the main apt cache
	my $main_src = `apt-cache showsrc $_[0] 2>/dev/null`;
	return if (!$main_src);
	$main_src =~ /Version: (.*)\n/g;
	$main_src = $1;
}

sub parse_gcc_dir
{
	my $result;
	my $r;
	my $dir;
	if ($forcing == 0)
	{
		$result = &binlookup($gcc_vers);
		$dir = $result->{VerStr};
	}
	else
	{
		$result = `apt-cache show $gcc_vers 2>/dev/null`;
		return "" if (!$result);
		$r = $result;
		$r =~ /Version: (.*)\n/g;
		$dir = $1;
		if (! -d $dir)
		{
			$dir =~ s/-[0-9]+$//;
		}
	}
	my $dsc = "${gcc_vers}_${dir}.dsc";
	$dsc =~ s/\n//;
	my $pat = "${gcc_vers}_.*orig\.tar.*";
	my $orig;
	if ( -f $dsc)
	{
		open (F, "$dsc");
		while(<F>)
		{
			if (/$pat/)
			{
				$orig = $_;
			}
		}
	}
	if (defined $orig)
	{
		$orig =~ s/\.orig\.tar\..*//;
		$orig =~ s/.* //;
		$orig =~ s/\_/\-/;
		$orig =~ s/\n//;
		return $orig if (-d $orig);
	}
	# less favourable method.
	if (! -d $dir) {
		$r = $result;
		$r =~ /Source: $gcc_vers \((.*)\)\n/;
		my $t = &split_debian($1);
		if (-d "$gcc_vers-$t") {
			return "$gcc_vers-$t"
		}
	}
	return "$gcc_vers-$dir";
}

sub get_src_dir
{
	my $pkg=$_[0];
	my $res = &binlookup($pkg);
	my $dir = $res->{VerStr};
	$dir =~ s/-.*\n?$//;
	return "$pkg-$dir";
}

sub uclibc_add_alias
{
	$_ = shift;
	my $src = shift;
	my $tgt = shift;
	s/^(([^!{]*\|)*static-libgcc)((\|[^:|]*)*:)/$1|uclibc$3/;
	s/^(!static-libgcc:)(.*)$/$1\%{!uclibc:$2}/;
	my $ret;
	for(;;)
	{
		my @res = extract_bracketed($_, '{}', '[^{]*');
		if(!$res[0])
		{
			$ret .= $_;
			return $ret;
		}
		$ret .= $res[2];
		my $child = $res[0];
		$child =~ s/^{(.*)}$/$1/;
		$ret .= '{' . &uclibc_add_alias($child, $src, $tgt) . '}';
		$_ = $res[1];
	}
}

sub uclibc_munge_specs
{
	print GREEN, "Converting gcc specs for use with uClibc.\n", RESET
		if ($verbose >= 1);
	my @s = split(/\n/, shift);
	my @ret = ();
	foreach my $line (@s)
	{
		if($line =~ /^\*([0-9A-Za-z_]*):$/)
		{
			push @ret, $line;
			next;
		}
		$line =~ s/(\%{I\*[^}]*})/$1 \%{uclibc:-I\/usr\/$arch\/include}/g;
		$line =~ s/(\%{L\*[^}]*})/$1 \%{uclibc:-L\/usr\/$arch\/lib}/g;
		$line =~ s/((S|g|)crt(0|1|i|n)(.o|\%O))(\%s)?/\%{uclibc:\/usr\/$arch\/lib\/$1;:$1$5}/g;
		$line =~ s/(\/lib\/ld-linux.so.2)/\%{uclibc:\/lib\/ld-uClibc.so.0;:$1}/g;
		if($line =~ /static-libgcc/)
		{
			# "uclibc" behaves like "static-libgcc"
			$line = &uclibc_add_alias($line, 'uclibc', 'static-libgcc');
		}
		push @ret, $line;
	}
	return join("\n", @ret);
}

sub uclibc_translate_triplet
{
	my $glibc_triplet = shift;
	return undef unless (defined $glibc_triplet);
	my $uclibc_triplet = $glibc_triplet;
	$uclibc_triplet =~ s/([[:alnum:]]*)-([[:alnum:]]*)-gnu(.*)/$1-$2-uclibc$3/;
	return undef if($glibc_triplet eq $uclibc_triplet);
	return $uclibc_triplet;
}

# generate a fake binutils package with the correct target triplet
sub uclibc_build_binutils
{
	my $uclibc_target = shift;
	return unless (defined $uclibc_target);
	my $binutils_pkg = "binutils-${uclibc_target}";
	print GREEN, "Building $binutils_pkg for $uclibc_target\n", RESET
		if ($verbose >= 2);
	system ("mkdir -p debian/${binutils_pkg}/usr/bin");
	system ("mkdir -p debian/${binutils_pkg}/usr/share/doc/${binutils_pkg}");
	my (@binutils) = `dpkg -L binutils-${target_gnu_type}`;
	foreach my $file (@binutils)
	{
		chomp($file);
		next unless $file =~ m:/usr/bin/${target_gnu_type}:;
		$file =~ s:/usr/bin/${target_gnu_type}-::;
		print CYAN, "symlinking : $file\n", RESET if ($verbose >= 3);
		unlink ("debian/${binutils_pkg}/usr/bin/${uclibc_target}-$file") if
			(-f "debian/${binutils_pkg}/usr/bin/${uclibc_target}-$file");
		my $e = symlink $file, "debian/${binutils_pkg}/usr/bin/${uclibc_target}-$file";
	}
	$uclibc_vers = $binutils_vers;
	mkdir ("debian/${binutils_pkg}/DEBIAN");
	open (CTRL, ">debian/control");
	print CTRL &uclibc_control_info ("$binutils_pkg");
	close (CTRL);
	system ("dpkg-gencontrol -p${binutils_pkg} -Pdebian/${binutils_pkg} ".
		"-cdebian/control");
	system ("dpkg-deb --build debian/${binutils_pkg} ..");
	`rm -rf ./debian` if (-d "debian");
	# end of binutils package.
	if ( -f "$workdir/${binutils_pkg}_${binutils_vers}_all.deb")
	{
		print GREEN;
		system ("ls -l $workdir/${binutils_pkg}_${binutils_vers}_all.deb");
		print RESET."\n";
	}
}

sub uclibc_build_chain
{
	my $check = &check_toolchains($arch, $target_gnu_type);
	# mismatch of host arches. Make sure that this also catches non-ia32 mismatches
	if ($check ne "true" and $arch eq "i386") {# and `dpkg-architecture -qDEB_BUILD_ARCH -ei386 2> /dev/null`) {

		# check is true since in this particular case (where
		# dpkg-architecture -qDEB_BUILD_ARCH -ei386
		# or other -e ) we have to check for these packages instead:
		# gcc, binutils, etc. i.e. the native ones.
		$check = "true";
		# getting ugly. While distinct subarches, they are treated
		# the same for ia32.
		# See: COLUMNS=150 dpkg -l "gcc-???-i?86-linux-*" | awk '{if (/gcc/)print $2}'
		# gcc-4.2-i486-linux-gnu-base
		# gcc-4.3-i486-linux-gnu
		# gcc-4.3-i486-linux-uclibc
		# i.e. nothing for i386 (the primary arch name) but only for
		# subsrches! Thus prevent havoc:
		$arch="i486";
	}
	if ($check ne "true")
	{
	# need to identify the relevant gcc version from the installed toolchain.
		my @dpkg_gcc = `dpkg -l "gcc-???-$arch-linux-gnu"`;
		my %gcc_list=();
		my $choice = 0;
		foreach my $install (@dpkg_gcc)
		{
			next unless $install =~ /^ii/;
			$install =~ s/^ii\s+//;
			$install =~ s/ +/ /g;
			my @bits = split(/ /, $install);
			if ($bits[0] =~ /gcc-([0-9\.]+)\-${target_gnu_type}$/)
			{
				if ($1 > $choice)
				{
					$choice = $1;
					$gcc_list{$choice}=$bits[1];
				}
			}
		}
		die ("check_toolchains failed") if ($choice == 0);
		$gcc_latest = $choice;
		$gcc_pkg_v = $gcc_list{$choice};
		my @dpkg_binutils = `dpkg -l "binutils-$arch-linux-gnu"`;
		foreach my $install (@dpkg_gcc)
		{
			next unless $install =~ /^ii/;
			$install =~ s/^ii\s+//;
			$install =~ s/ +/ /g;
			my @bits = split(/ /, $install);
			$binutils_vers = $bits[1];
		}
		print "binutils_vers=$binutils_vers\n";
	}
	print CYAN, wrap ('','',"Creating uclibc toolchain packages for :",
		"$target_gnu_type in $workdir\n"), RESET if ($verbose >= 1);
	my $dir = "uclibc-${target_gnu_type}";
	mkdir ($dir) if (! -d "debian");
	chdir($dir);
	`rm -rf ./debian` if (-d "debian");
	my $uclibc_target = &uclibc_translate_triplet($target_gnu_type);
	my $gcc_package = "gcc-${gcc_latest}-${uclibc_target}";
	$binutils_pkg = "binutils-${uclibc_target}";
	my $gpp_package = "g++-${gcc_latest}-${uclibc_target}";
	# cross-gcc Depends:
	$binutils_cross = "binutils-${target_gnu_type}";
	# Check if we are doing a cross-compiler for a different libc or subarch
	my $host_arch = `dpkg-architecture -qDEB_BUILD_ARCH`;
	my $tgt_arch = $arch;
	$tgt_arch =~ s/i.86/i386/;
	chomp($host_arch);
	if ($host_arch eq $tgt_arch) {
		# Setup the Depends: field of the fake-gcc we are about to build
		# - We are using the same arch.
		# - Binutils is libc-agnostic
		# - Binutils can generate code for all subarches, so we
		#   can cater for the inexactness later on via flags.
		$binutils_cross = "binutils";
		$binutils_pkg   = "binutils";
	} else {
		# generate a faked package with the needed target triplet
		&uclibc_build_binutils(${uclibc_target});
	}
	print GREEN, "Building $gcc_package for $uclibc_target\n", RESET
		if ($verbose >= 2);
	system ("mkdir -p debian/${gcc_package}/usr/bin");
	system ("mkdir -p debian/${gcc_package}/usr/share/doc/${gcc_package}");
	my $gcc_shell = "debian/${gcc_package}/usr/bin/${uclibc_target}-gcc";
	open(GCC, ">$gcc_shell");
	print (GCC "#!/bin/sh\n");
	print (GCC "${target_gnu_type}-gcc -uclibc \"\$\$@\"\n");
	close (GCC);
	chmod (0755, $gcc_shell);
	my @search = `${target_gnu_type}-gcc -print-search-dirs`;
	my $target_compiler;
	foreach my $dir (@search)
	{
		next unless $dir =~ /^install: /;
		$dir =~ s/install: //;
		$target_compiler = $dir;
		chomp($target_compiler);
	}
	die unless (defined $target_compiler);
	print GREEN, "Creating target_compiler directory tree : $target_compiler\n",
		RESET if ($verbose >= 3);
	system ("mkdir -p debian/${gcc_package}/${target_compiler}");
	my $gccspecs = `$arch-linux-gnu-gcc -dumpspecs`;
	my $s = &uclibc_munge_specs($gccspecs);
	open (SPECS, ">debian/${gcc_package}/${target_compiler}/specs");
	print SPECS "$s\n";
	close (SPECS);
	mkdir ("debian/${gcc_package}/DEBIAN");
	open (PREINST, ">debian/${gcc_package}/DEBIAN/preinst") or die (
	"Cannot create debian/$gcc_package/DEBIAN/preinst: $!");
	print PREINST "#!/bin/sh\n";
	print PREINST "dpkg-divert --package ${gcc_package} --add --rename --divert ${target_compiler}specs.glibc ${target_compiler}specs\n";
	close (PREINST);
	chmod (0755, "debian/${gcc_package}/DEBIAN/preinst");
	open (POSTRM, ">debian/${gcc_package}/DEBIAN/postrm");
	print POSTRM "#!/bin/sh\n";
	print POSTRM "dpkg-divert --package ${gcc_package} --rename --remove ${target_compiler}specs\n";
	close (POSTRM);
	chmod (0755, "debian/${gcc_package}/DEBIAN/postrm");
	open (CTRL, ">debian/control");
	$uclibc_vers = $gcc_pkg_v;
	print CTRL &uclibc_control_info ("$gcc_package");
	close (CTRL);
	system ("dpkg-gencontrol -p${gcc_package} -Pdebian/${gcc_package} ".
		"-cdebian/control");
	system ("dpkg-deb --build debian/${gcc_package} ..");
	if ( -f "$workdir/${gcc_package}_${gcc_pkg_v}_all.deb")
	{
		print GREEN;
		system ("ls -l $workdir/${gcc_package}_${gcc_pkg_v}_all.deb");
		print RESET, "\n";
	}
}

sub uclibc_control_info
{
	my ($target, $target_gcc_vers, $target_arch, $std_ver);
	$std_ver = &get_standards_version;
#	echo >>debian/$(cross_package).substvars 'target:GCCVersion=$(shell dpkg -s
# gcc-4.1-$(glibc_target) | sed -ne "s/Version: //p")'
	$target = shift;
	$target_gcc_vers = $gcc_pkg_v;
#	$target_arch = "foo";
	my $maint = defined($ENV{DEBFULLNAME}) ? $ENV{DEBFULLNAME} : "Simon Richter";
	$maint .= defined($ENV{DEBEMAIL}) ? " <".$ENV{DEBEMAIL}.">" : '<sjr@debian.org>';
	print CYAN, "changelog maintainer : $maint\n", RESET if ($verbose >= 2);
	my $pkgpath = "debian/${target}";
	my $docpath = "/usr/share/doc/${target}/";
	unlink ("${pkgpath}${docpath}/changelog");
	unlink ("${pkgpath}${docpath}/copyright");
	&uclibc_changelog("$target");
	open (COPY, "<debian/changelog");
	my @c=<COPY>;
	close (COPY);
	open (CLOG, ">${pkgpath}${docpath}/changelog");
	print CLOG @c;
	close (CLOG);
	unlink ("${pkgpath}${docpath}/changelog.gz");
	`gzip -9 "${pkgpath}${docpath}/changelog"`;
	print CYAN, "Auto-generating copyright information.\n", RESET if ($verbose >= 2);
	open (COPY, ">${pkgpath}${docpath}/copyright");
	print COPY &uclibc_copyright;
	close (COPY);
	my $ctrl = qq%Source: ${target}
Section: devel
Priority: extra
Maintainer: $maint
Build-Depends: debhelper (>= 5)
Standards-Version: $std_ver

Package: ${target}
Architecture: all%;
	if ($target =~ /^binutils/)
	{
		$ctrl .= qq%
Depends: ${binutils_cross}
Description: binutils support for building against uClibc
 This package provides wrapper scripts for the toolchain, providing an
 alternate host triplet for building against uclibc.
%;
	}
	if ($target =~ /^gcc/)
	{
		$ctrl .= qq%
Depends: gcc-${gcc_latest}-${target_gnu_type} (= ${gcc_pkg_v}),
 libuclibc-dev-${arch}-cross, ${binutils_pkg}
Description: Toolchain alias for building against uclibc
 This package provides wrapper scripts for the toolchain, providing an
 alternate host triplet for building against uclibc.
%;
	}
	return $ctrl;
}

sub uclibc_changelog
{
	my $name = defined($ENV{DEBFULLNAME}) ? $ENV{DEBFULLNAME} : "Simon Richter";
	my $email .= defined($ENV{DEBEMAIL}) ? $ENV{DEBEMAIL} : 'sjr@debian.org';
	my $maint = "$name <$email>";
	my $cross_package = shift;
	# dch doesn't support entirely automated changelogs from new :-(
	open (CLOG, ">debian/changelog");
	print CLOG "$cross_package ($uclibc_vers) UNRELEASED; urgency=low\n\n";
	print CLOG "  * Automated package.\n\n";
	print CLOG " -- $maint  Sat, 29 Mar 2008 14:22:41 +0000\n";
	close (CLOG);
	# ensure the timestamp is updated.
	`DEBFULLNAME="$name" DEBEMAIL="$email" dch -r automated package`;
}

sub uclibc_copyright
{
	my $copy = qq%This package was automatically generated by emdebian-tools for use with uClibc.

Files: *
Licence: GPL-2+
Copyright: 2007-2008 Neil Williams <codehelp\@debian.org>
           2007-2008 Simon Richter <sjr\@debian.org>

   This package is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 dated June, 1991, or
   (at your option) any later version.

   This package is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this package; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
   MA 02110-1301, USA.

On Debian systems, the complete text of the GNU General
Public License can be found in `/usr/share/common-licenses/GPL-2'
%;
	return $copy;
}

sub tools_version {
	my $query = `dpkg-query -W -f='\${Version}' emdebian-crush`;
	(defined $query) ? return $query : return "2.2.0";
}

sub host_arch
{
	my $result = `dpkg-architecture -qDEB_HOST_ARCH`;
	chomp ($result);
	return $result;
}

sub get_standards_version
{
	return "3.8.0";
}

sub check_emdebian_control
{
	my $pkg;
	# check this is a debian working directory
	# read debian/control
	# parse for locale packages.
	until (-f "debian/control")
	{
		chdir ".." or die "Cannot change directory ../ $!";
		if (cwd() eq '/')
		{
			die "Cannot find debian/control anywhere!\nAre you in the source code tree?\n";
		}
	}
}

sub prepare_checklist
{
	my $arch = shift;
	my $target_gnu_type = shift;
	push my @list ,"binutils-${target_gnu_type}";
	push @list, "${gcc_vers}-${target_gnu_type}-base";
	push @list, "${gcc_vers}-${target_gnu_type}";
	push @list, "cpp-${gcc_latest}-${target_gnu_type}";
	push @list, "g++-${gcc_latest}-${target_gnu_type}";
	push @list, "${libc_vers}-${arch}-cross";
	push @list, "${libc_vers}-dev-${arch}-cross";
	push @list, "libstdc++${libc_latest}-${arch}-cross";
	push @list, "libstdc++${libc_latest}-${gcc_latest}-dev-${arch}-cross";
	push @list, "libstdc++${libc_latest}-${gcc_latest}-pic-${arch}-cross";
	push @list, "libgcc1-${arch}-cross";
	push @list, &check_linux($arch);
	my $multilib;
	my $our_arch = `dpkg-architecture -qDEB_BUILD_ARCH`;
	chomp ($our_arch);
	$multilib = "libc6-dev-i386" if ($our_arch =~ /^amd64$/);
	push @list, $multilib if (defined $multilib);
	return \@list;
}

sub check_linux
{
	my $arch = $_[0];
	my $query = `dpkg-query -W -f=' \${Package} \${Status}' linux-kernel-headers 2>/dev/null`;
	return "linux-kernel-headers-${arch}-cross"
		if ($query eq " linux-kernel-headers install ok installed");
	return "linux-libc-dev-${arch}-cross";
}

sub check_toolchains
{
	my $arch = shift;
	my $target = shift;
	my $retval = "true";
	my $list = &prepare_checklist($arch, $target);
	my $status = 'install ok installed';
	my $success = "";
	my $string = " ";
	foreach my $res (sort @$list)
	{
		$success = `dpkg-query -W -f='\${Package} \${Status}' $res 2>/dev/null`;
		$string = "$res $status";
		$retval = "false" if ($success ne $string);
	}
	return $retval;
}
