#!/usr/bin/perl -w

=head1 NAME

dh_pycmakedeps - detect dependencies in Python modules compiled with CMake

=cut

use strict;
use File::Find;
use Debian::Debhelper::Dh_Lib;

=head1 SYNOPSIS

B<dh_pycmakedeps> [I<debhelper options>] B<--modules-root=>I<modules root directory>

=head1 DESCRIPTION

=head1 OPTIONS

=over 1

=item B<--modules-root=>I<PySide>

=back

=cut

init(options => {
	"modules-root=s" => \$dh{MODULES_ROOT},
});

foreach my $package (@{$dh{DOPACKAGES}}) {
	my $tmp = tmpdir($package);
	my $ext=pkgext($package);

	my $substvars="debian/${ext}substvars";

	my $install=pkgfile($package,'install');
	
	if ($install) {
		my @installModules=filearray(${install});
		
		# Determine the modules name (can have more than 1)
		foreach my $installModule (@installModules) {
			my @allInstall;
			# Don't mix python2 and python3 modules
			if ( $installModule =~ m/\.cpython-.*\.so/ ) {
				@allInstall=glob('debian/python3-pyside2.*.install');
			} else {
				@allInstall=glob('debian/python-pyside2.*.install');
			}
			# Only take those that are explicitely named
			if ( $installModule =~ m/.so$/ and $installModule =~ s/^.*\/([a-zA-Z]*)(\.cpython.*)?\.so$/$1/g ) {
				# Go along them
				foreach my $module ($installModule) {
					# Parse the CMakeLists to find the dependencies
					my $file=$dh{MODULES_ROOT}.${module}.'/CMakeLists.txt';
				        open (CMAKEFILE, $file) || error("cannot read $file: $1");
				        while (<CMAKEFILE>) {
				                chomp;
                				my $line = $_;
						# Dependencies
						# if ( $line =~ s/add_dependencies\(${module} (.*)\)/$1/ ) {
						if ( $line =~ s/set\(${module}_deps (.*)\)/$1/ ) {
						$line =~ s/^"(.*)"$/$1/; # Strip single quotes.
						print ${module}."=>".$line."\n";
							foreach my $module_dep (split(' ',$line)) {
								# Find the modules packages
								foreach my $other_package_install (@allInstall) {
									my @opi_content = filearray($other_package_install);
									foreach my $opi_line (@opi_content) {
										if( $opi_line =~ m/\/${module_dep}(.cpython.*)?.so$/ ) {
											my $other_package_name = $other_package_install;
											$other_package_name =~ s/debian\/(.*)\.install/$1/;
											if ( $package ne $other_package_install ) {
												addsubstvar($package, "pycmakedeps:Depends", "$other_package_name (= \${binary:Version})");
											}
										}
									}
								}
							}
						}
        				}
				        close CMAKEFILE;
				}
			}
		}
	}
}

=head1 SEE ALSO

L<debhelper(7)>

This program is a part of the pyside packaging but is made to work with debhelper.

=head1 AUTHORS

Didier Raboud <didier@raboud.com>

=cut
