#!/usr/bin/perl -w
#
#  emsetup -- Check system for emdebian setup
#
#  based on em_make and emchain
#
#  Checks for previous apt-get operations on the emdebian
#  repository and checks for the presence of a usable toolchain,
#  before using debconf to ask the user to complete their setup.
#
#  Copyright (C) 2006, 2007  Neil Williams <codehelp@debian.org>
#
#  This program 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 2 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, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#

use Cwd;
use File::HomeDir;
use Debian::Debhelper::Dh_Lib;
use Emdebian::Tools;
use Config::Auto;
use warnings;
use strict;
use vars qw($unstable $testing $stable @ret $suite $arch $status $progname $verbose $dry $chain_msg $available %archtable $report_only $no_upstream );
require "dpkg-cross.pl";
my $ourversion = "0.2.0";

&read_config();
$arch = &get_architecture();
$verbose = 1;
$dry = 0;
$report_only = 0;
$no_upstream = 0; # set if no pre-built toolchain exists.

# recommend emchain if necessary.

$chain_msg = 
qq/If you do not wish to use the emdebian toolchain repository or if a toolchain
 for your chosen target architecture is not yet available for your host architecture,
 please consider using emchain (part of emdebian-tools) to build a cross-building
 toolchain that fits your needs.\n\n/;

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

Usage:
 emsetup [-a|--arch ARCH] [-s|--simulate] [-v|--verbose] [-q|--quiet]
 emsetup [-a|--arch ARCH] --report
 emsetup -h|--help|--version

Options:
 -a|--arch ARCH:      set architecture (default: defined by dpkg-cross)
 -s|--simulate:       Do a dry-run, do not change anything.
    --report:         Report on the installed toolchain
 -v|--verbose:        Increase verbosity (max: 3)
 -q|--quiet:          Reduce verbosity.
 -h|--help:           print this usage message and exit
 --version:           print this usage message and exit

emsetup checks your system for emdebian compatibility and support.

If a compatible toolchain is already installed, emsetup does nothing. If
a toolchain is available for your host architecture to build the specified
target architecture, it will be installed for you using sudo.

To see what emsetup would do without changing your existing system, use
--simulate.

To see which packages emsetup has checked, use --report.

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

while( @ARGV ) {
    $_= shift( @ARGV );
    last if m/^--$/;
    if (!/^-/) {
        unshift(@ARGV,$_);
		last;
    }
	elsif (/^(-h|--help|--version)$/) {
        &usageversion();
		exit( 0 );
	}
	elsif (/^(-v|--verbose)$/) {
		$verbose++;
	}
	elsif (/^(-s|--simulate)$/) {
		$dry = 1;
	}
	elsif (/^(-q|--quiet)$/) {
		$verbose--;
	}
	elsif (/^(-a|--arch)$/) {
		$arch = shift(@ARGV);
	}
	elsif (/^(--report)$/) {
		$report_only = 1;
	}
	else {
		die "$progname: Unknown option $_.\n";
	}
}

die("Could not determine the default architecture, please use $progname --arch\n") if (!$arch);
die(qq;\nError: dpkg-cross does not currently support "$arch"\n;) if (!$archtable{$arch});

# Try to determine the current suite.
$suite = &get_suite();
my $target_gnu_type = $archtable{$arch};

# ensure that the apt-cross setup is complete
# without forcing an update.
my $q = "";
$q = "-v" if ($verbose >= 2);
$q = '-q' if ($verbose < 1);
`apt-cross $q -a $arch -l`;

if ($report_only == 1)
{
		&report_env($chain_msg);
		exit(0);
}

print "Dry run only.\n" if (($dry >= 1) && ($verbose >= 1));

# check sources.list -> modify -> update
# done in preinst now.
#my $repo = &check_ourrepo;
#&modify_sources if (!$repo);

# If a toolchain is found stop immediately; if the user can create a 
# toolchain themselves, they don't need setup help.
my $check = &check_toolchains($arch, $target_gnu_type);
if($check eq "true")
{
	print "\nSetup appears OK for Emdebian. Nothing to do.\n\n" if ($verbose >=1);
	exit;
}

# check availability
my $gcc_latest =  &find_latest_gcc("gcc", $arch, $suite);
if ($gcc_latest eq "0")
{
	print "Updating apt cache data ...\n";
	`apt-cross -v -a $arch -u`;
	$gcc_latest =  &find_latest_gcc("gcc", $arch, $suite);
	if ($gcc_latest eq "0")
	{
		# if still no result, check the main Debian cache
		print "Cannot find a native gcc for $arch.\n" if ($verbose >= 1);
		my $host_arch = &host_arch;
		print "Trying to locate latest version of gcc for $host_arch.\n" if ($verbose >= 1);
		my $dpkg_cross_dir = &get_dpkg_cross_dir;
		# use our conf to get results only for the value of $suite
		# when #416241 is fixed, this duplicate update can be removed.
		# along with the third update later to reinstate the $arch cache.
		`apt-get -c $dpkg_cross_dir/apt.conf-$suite update`;
		my $result = `apt-cache -o Apt::Architecture=$host_arch -c $dpkg_cross_dir/apt.conf-$suite pkgnames gcc 2>/dev/null`;
		my @list = split (/\n/, $result);
		my $choice = 0;
		foreach my $line (@list)
		{
			if ($line =~ /gcc-([0-9\.\-]*)$/)
			{
				if ($1 > $choice) { $choice = $1; }
			}
		}
		$gcc_latest = $choice;
		$no_upstream = 1;
	}
	die("\nError: $progname is unable to proceed - cannot find gcc for $arch!\n") 
		if ($gcc_latest eq "0");
}
my $gcc_vers = "gcc-" . $gcc_latest;

$available = "true";
my $report = `apt-cache policy ${gcc_vers}-${target_gnu_type} 2>/dev/null`;
$available = "false" if (!$report);

&install_toolchain() if ($available eq "true");

if ($available eq "false")
{
	my $host = &host_arch();
	my $msg = "Unable to find a suitable toolchain to build '$arch' targets on '$host'.\n";
	print $msg;
	print "Please consider using emchain to build your own toolchain.\n" if ($verbose >= 1);
	print $chain_msg if ($verbose >= 2);
	if ($verbose >= 1)
	{
		my $list = ($no_upstream == 0) ? &prepare_checklist($arch, $target_gnu_type)
			: &prepare_checklist($host, $target_gnu_type);
		print "Packages required for '$arch' on '$host':\n";
		foreach my $pkg (@$list)
		{
			print "$pkg ";
		}
		print "\n";
	}
	print "\nOnce a suitable toolchain can be installed, setup will be complete.\n";
	print "Use '$progname --report' to check just the toolchain.\n" if ($verbose >= 2); 
}

sub report_env
{
	print "Updating apt cache data ...\n" if ($verbose >= 1);
	`apt-cross -a $arch -u`;
	my $host = &host_arch();
	$gcc_latest =  &find_latest_gcc("gcc", $arch, $suite);
	if ($gcc_latest eq "0")
	{
		my $msg = "Unable to find a suitable toolchain to build '$arch' targets on '$host'.\n";
		print $msg;
		print "Please consider using emchain to build your own toolchain.\n" if ($verbose >= 1);
		print $_[0] if ($verbose >= 2);
		exit;
	}
	$suite = &get_suite();
	my $list = &prepare_checklist($arch, $target_gnu_type);
	my $success = "";
	my $string = "";
	foreach my $pkg (@$list)
	{
		$string .= " $pkg";
	}
	$success = `dpkg-query -W -f=' \${Package}' $string 2>/dev/null`;
	if ($success eq $string)
	{
		system ("dpkg -l $string");
		return;
	}
	if ($success ne $string)
	{
		print "Unable to find a toolchain suitable for Emdebian on $arch.\n";
		print "Searched for:\n";
		foreach my $pkg (@$list)
		{
			print "$pkg\n";
		}
	}
}

# superceded - due to be removed.
sub modify_sources
{
	if ($dry >= 1)
	{
		print "Need to add the emdebian toolchain repository to sources list.\n";
		return;
	}
	my $suite = &get_suite;
	open(SOURCES, ">>/etc/apt/sources.list");
	print SOURCES "\ndeb http://www.emdebian.org/debian/ $suite main\n";
	close (SOURCES);
	my $msg = "Running sudo apt-get update - enter your sudo password if prompted.\n";
	print $msg if ($verbose >=1);
	system "sudo apt-get update";
}

sub install_toolchain
{
	my $host = &host_arch();
	my $install = "";
	my $list = &prepare_checklist($arch, $target_gnu_type);
	foreach my $pkg (@$list)
	{
		$install .= " $pkg";
	}
	my $aptagent = &get_aptagent;
	$aptagent = "apt-get" if (!$aptagent);
	if ($dry >= 1)
	{
		print "Need to install an emdebian toolchain to build '$arch' on '$host'.\n";
		print "sudo $aptagent install $install\n" if ($verbose >= 2);
		return;
	}
	my $msg = "Running sudo $aptagent install - enter your sudo password if prompted.\n";
	print $msg if ($verbose >=1);
	system "sudo $aptagent install $install";
}
