# A debhelper build system class for handling simple mk-configure-based projects.
#
# Copyright: © 2008 Joey Hess
#            © 2008-2009 Modestas Vainius
# License: GPL-2+

package Debian::Debhelper::Buildsystem::mkcmake;

use strict;
use Debian::Debhelper::Dh_Lib qw(compat escape_shell clean_jobserver_makeflags dpkg_architecture_value);
use base 'Debian::Debhelper::Buildsystem::makefile';

sub DESCRIPTION {
	"mk-configure"
}

sub exists_make_target {
	my ($this, $target) = @_;

	# Use -V .ALLTARGETS to get the list of targets; -n is
	# needed to avoid executing anything
	my @opts=("-n", "-V", ".ALLTARGETS");
	my $buildpath = $this->get_buildpath();
	unshift @opts, "-C", $buildpath if $buildpath ne ".";
	open(SAVEDERR, ">&STDERR");
	open(STDERR, ">/dev/null");
	open(MAKE, "-|", $this->{makecmd}, @opts);
	my $output=<MAKE>;
	chomp $output;
	close MAKE;
	open(STDERR, ">&SAVEDERR");
	return defined $output && grep(/^$target$/, split(" ",$output));
}

# Currently, we don't want parallel build with bmake.
sub do_make {
	my $this=shift;

	# Avoid possible warnings about unavailable jobserver,
	# and force make to start a new jobserver.
	clean_jobserver_makeflags();

	my @opts;
	my $prefix = "/usr";
	push @opts, "PREFIX=${prefix}";
	push @opts, "MANDIR=${prefix}/share/man";
	push @opts, "INFODIR=${prefix}/share/info";
	push @opts, "SYSCONFDIR=/etc";
	my $multiarch=dpkg_architecture_value("DEB_HOST_MULTIARCH");
	if (! compat(8)) {
		   if (defined $multiarch) {
					push @opts, "LIBDIR=${prefix}/lib/$multiarch";
					push @opts, "LIBEXECDIR=${prefix}/lib/$multiarch";
			}
			else {
					push @opts, "LIBEXECDIR=${prefix}/lib";
			}
	}
	else {
			push @opts, "LIBEXECDIR=${prefix}/lib/" . sourcepackage();
	}

	$this->doit_in_builddir($this->{makecmd}, @opts, @_);
}

sub check_auto_buildable {
	my $this=shift;
	my ($step)=@_;

	if (-e $this->get_buildpath("makefile") ||
	    -e $this->get_buildpath("Makefile"))
	{
        my $ret = ($this->SUPER::check_auto_buildable(@_));

        open (MAKEFILE, "makefile") || open (MAKEFILE, "Makefile") ||
            return 0;

        while (<MAKEFILE>) {
                chomp;
                if (/^\.?\s*include\s+<mkc/) {
                        close MAKEFILE;
                        $ret++;
                        return $ret;
                }
        }
        close MAKEFILE;
        return $ret;
	}
	return 0;
}

sub new {
	my $class=shift;
	my $this=$class->SUPER::new(@_);
	$this->{makecmd} = "mkcmake";
	return $this;
}

1
