#!/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 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 Debian::Debhelper::Dh_Lib;
use Debian::DpkgCross;
use Cache::Apt::Lookup;
use Cache::Apt::Config;
use Emdebian::Tools;
use Term::ANSIColor qw(:constants);
use Text::Wrap;
use Config::Auto;
use warnings;
use strict;
use vars qw($unstable $testing $stable @ret $suite $arch $status
$progname $verbose $dry $chain_msg $available $report_only
$no_upstream $yes $deb_host_gnu_type);

my $ourversion = &tools_version();

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

# 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] [-y|--yes]
 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.
 -y|--yes:            Proceed with toolchain installation without confirmation.
 -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;
	}
	elsif (/^(-y|--yes)$/) {
		$yes = "--yes";
	}
	else {
		die "$progname: Unknown option $_.\n";
	}
}

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

# Try to determine the current target suite.
$suite = &get_targetsuite();
my $target_gnu_type = &check_cache_arch($arch);

# ensure that the apt-cross setup is complete
# without forcing an update.
my $q = "";
$q = "-v" if ($verbose >= 1);
$q = '-q' if ($verbose < 1);
print CYAN, "Checking apt cache data is up to date ...\n", RESET;
&check_update($verbose);
&check_hostconfig;

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

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

# If a toolchain is found stop immediately; if the user can create a
# toolchain themselves, they don't need setup help.
# add an OK here if arch = target
my $check = &check_toolchains($arch, $target_gnu_type);
if($check eq "true")
{
	print GREEN, "\nSetup appears OK for Emdebian. Nothing to do.\n\n", RESET if ($verbose >=1);
	exit;
}
my $gcc_latest = &check_availability($arch, $suite);
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 RED, $msg, RESET;
	print CYAN, "Please consider using emchain to build your own toolchain.\n", RESET 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 CYAN, "Packages required for '$arch' on '$host':\n", RESET;
		foreach my $pkg (@$list)
		{
			print GREEN, "$pkg ", RESET;
		}
		print "\n";
	}
	print CYAN, "\nOnce a suitable toolchain can be installed, setup will be complete.\n", RESET;
	print CYAN, "Use '$progname --report' to check just the toolchain.\n", RESET if ($verbose >= 2);
	# return zero to retain chroot integrity.
	exit 0;
}
exit 0;

sub report_env
{
	&check_update($verbose);
	my $host = &host_arch();
	$gcc_latest = &check_availability($arch, $suite);
	my $gcc_vers = "gcc-" . $gcc_latest;
	my $report = `apt-cache policy ${gcc_vers}-${target_gnu_type} 2>/dev/null`;
	if (!$report)
	{
		my $msg = "Unable to find a suitable toolchain to build '$arch' targets on '$host'.\n";
		print RED, $msg, RESET;
		print CYAN, "Please consider using emchain to build your own toolchain.\n", RESET if ($verbose >= 1);
		print $_[0] if ($verbose >= 2);
		# set nonzero so that scripts can use --report to check chroot suitability.
		exit 1;
	}
	print GREEN, "Emdebian toolchain for $arch is available for $host\n", RESET if ($verbose >= 1);
	$suite = &get_targetsuite();
	print CYAN, "Checking if toolchain packages are already installed ...\n", RESET if ($verbose >= 1);
	my $success = &check_toolchains($arch, $target_gnu_type);
	my $list = &prepare_checklist($arch, $target_gnu_type);
	my $string = join (' ', @$list);
	if ($success eq "true")
	{
		print CYAN, "dpkg -l $string 2>/dev/null\n", RESET if ($verbose >= 2);
		print GREEN, "\nSetup appears OK for Emdebian. Report follows:\n\n", RESET if ($verbose >=1);
		# the output doesn't optimise nicely - separate parsing would be needed
		# to only get the first line of the Description, dpkg-query outputs
		# the entire short+long description. For now, use the dpkg -l default.
		system ("dpkg -l $string 2>/dev/null");
		return;
	}
	if ($success eq "false")
	{
		# just show the errors.
		system ("dpkg-query -W -f=' \${Package}' $string 1>/dev/null");
		print RED, "Emdebian toolchain for $arch on $host is available but not installed.\n", RESET;
		print CYAN, wrap('','',"Searched for: $string\n"), RESET if ($verbose >= 2);
		print GREEN, "Testing installability with edosdebcheck, please wait . . . \n", RESET;
		print CYAN, wrap('','',"If any tests report a failure, please ask on the ",
			"debian-embedded mailing list: http://lists.debian.org/debian-embedded/",
			'debian-embedded@lists.debian.org. ',"See also 'man 1 emsetup'\n"), RESET;
		&run_edoscheck($string, $suite);
		print GREEN, "Use '$progname -a $arch' to install the $arch toolchain for $host.\n", RESET;
	}
}

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 CYAN, "An emdebian toolchain is available to build '$arch' on '$host'.\n", RESET;
		print GREEN, "sudo $aptagent install $yes $install\n", RESET if ($verbose >= 2);
		return;
	}
	my $msg = "Running sudo $aptagent install - enter your sudo password if prompted.\n";
	print GREEN, $msg, RESET if ($verbose >=1);
	system "sudo $aptagent install $yes $install";
}

sub check_availability
{
	# check availability
	my $arch = $_[0];
	my $suite = $_[1];
	my $gcc_latest =  &find_latest_gcc("gcc", $arch, $suite);
	if ($gcc_latest eq "0")
	{
		$gcc_latest =  &find_latest_gcc("gcc", $arch, $suite);
		if ($gcc_latest eq "0")
		{
			# if still no result, check the main Debian cache
			print RED, "Cannot find a native gcc for $arch.\n", RESET if ($verbose >= 1);
			my $host_arch = &host_arch;
			print CYAN, "Trying to locate latest version of gcc for $host_arch.\n", RESET if ($verbose >= 1);
			my %h = ();
			my $dpkg_cross_dir = &get_cachedir;
			&set_suite($suite);
			my $config = &init_host_cache(0);
			&cache_update($config);
			my $iter = &get_cache_iter();
			my $pkg;
			do {
				$pkg = $iter->next;
				$h{$pkg}++ if ($pkg);
			} while ($pkg);
			my @list = sort keys (%h);
			# use our conf to get results only for the value of $suite
			my $choice = 0;
			foreach my $line (@list)
			{
				if ($line =~ /gcc-([0-9\.\-]*)$/)
				{
					if ($1 > $choice) { $choice = $1; }
				}
			}
			$gcc_latest = $choice;
			$no_upstream = 1;
		}
		die("\n", RED, "Error: $progname is unable to proceed - cannot find gcc for $arch!", RESET, "\n")
			if ($gcc_latest eq "0");
	}
	return $gcc_latest;
}

sub check_hostconfig
{
	my $retval = 0;
	$retval = system("hostname -f 1>/dev/null");
	return if ($retval == 0);
	my $hostmsg = qq/$progname: Unable to determine fully qualified hostname. /;
	die RED, $hostmsg, RESET, "\n" if ($verbose == 1);
	$hostmsg .= "Please check your /etc/hosts file. See emsetup (1) ";
	$hostmsg .= "for more information.";
	die RED, wrap('','',$hostmsg), RESET, "\n";
}

sub run_edoscheck
{
	my $list = $_[0];
	my $suite = $_[1];
	my $dpkg_cross_dir = &get_cachedir;
	my $host = &host_arch();
	my %files=();
	opendir (PKG, "$dpkg_cross_dir/$suite/lists") or die ("Unable to check for packages files\n");
	my @pkgfiles=grep(!/^\.\.?/, readdir PKG);
	closedir (PKG);
	foreach my $file (@pkgfiles)
	{
		next unless $file =~ /_debian_dists_${suite}_main_binary-${host}_Packages$/;
		# only have one debian mirror and the emdebian one.
		$files{'debian'} = $file if ($file !~ /emdebian/);
		$files{'emdebian'} = $file if ($file =~ /www\.emdebian\.org/);
	}
	return if (not defined $files{'debian'} and not defined $files{'emdebian'});
	# cat the two packages files together, pass to edos-debcheck $string < file 2>/dev/null
	my $edosfile = `mktemp -t emsetupedos.XXXXXX`;
	chomp($edosfile);
	my $path = "$dpkg_cross_dir/$suite/lists/" . $files{'debian'};
	open (DEB, ">$edosfile") or die ("Unable to open temporary file\n");
	open (LIST, "<$path") or die ("Unable to open package list.\n");
	my @list=<LIST>;
	print DEB @list;
	close (LIST);
	@list = ();
	$path = "$dpkg_cross_dir/$suite/lists/" . $files{'emdebian'};
	open (LIST, "<$path") or die ("Unable to open package list.\n");
	@list=<LIST>;
	print DEB @list;
	close (LIST);
	close (DEB);
	system ("edos-debcheck $list < $edosfile 2>/dev/null");
	unlink($edosfile);
}
