# A debhelper build system class for building Pd-externals with pd-lib-builder.
#
# Copyright: © 2022 IOhannes m zmölnig
# License: GPL-2+

package Debian::Debhelper::Buildsystem::pd_lib_builder;

use strict;
use warnings;
use Debian::Debhelper::Dh_Lib qw(compat dpkg_architecture_value is_cross_compiling);
use Dpkg::Version qw();

use base 'Debian::Debhelper::Buildsystem::makefile';

sub DESCRIPTION {
    "pd-lib-builder based externals"
}

sub clean {
  my $this=shift;

  unshift(@_, "PDLIBBUILDER_DIR=/usr/share/pd-lib-builder/");

  return $this->SUPER::clean(@_);
}

sub build {
  my $this=shift;
  if (is_cross_compiling()) {
      # Inject build tools variables during cross-compile
      # this should really be fixed in debhelper...see #1024296
      my %DEB_DEFAULT_TOOLS = (
          'CC'		=> 'gcc',
          'CXX'		=> 'g++',
          'PKG_CONFIG'	=> 'pkg-config',
          );
      for my $var (sort(keys(%DEB_DEFAULT_TOOLS))) {
          my $tool = $DEB_DEFAULT_TOOLS{$var};
          if ($ENV{$var}) {
              unshift @_, $var . "=" . $ENV{$var};
          } else {
              unshift @_, $var . "=" . dpkg_architecture_value("DEB_HOST_GNU_TYPE") . "-" . $tool;
          }
      }
  }

  unshift(@_, "PDLIBBUILDER_DIR=/usr/share/pd-lib-builder/");
  unshift(@_, "CPPFLAGS=$ENV{CPPFLAGS}");
  unshift(@_, "CFLAGS=$ENV{CPPFLAGS} $ENV{CFLAGS}");
  unshift(@_, "LDFLAGS=$ENV{LDFLAGS}");
  unshift(@_, "arch.c.flags=");
  if (not compat(10)) {
    unshift @_, "INSTALL=install --strip-program=true";
  }

  return $this->SUPER::build(@_);
}

sub test {
  my $this=shift;

  unshift(@_, "PDLIBBUILDER_DIR=/usr/share/pd-lib-builder/");

  $this->SUPER::test(@_);
}

sub install {
  my $this=shift;
  my $destdir=shift;

  unshift(@_, "PDLIBBUILDER_DIR=/usr/share/pd-lib-builder/");
  unshift(@_, "prefix=/usr");
  unshift(@_, "pkglibdir=/usr/lib/pd/extra");
  if (not compat(10)) {
    unshift @_, "INSTALL=install --strip-program=true";
  }

  return $this->SUPER::install($destdir, @_);
}

1;
