#!/usr/bin/perl -w

=encoding utf8

=head1 NAME

dh_fortran_mod - Install Fortran 90 .mod files and add dependency information.

=cut

use strict;
use File::Find;
use Debian::Debhelper::Dh_Lib;
use IO::Uncompress::Gunzip qw( $GunzipError );
use File::LibMagic;

=head1 SYNOPSIS

B<dh_fortran_mod> [$<I<debhelper options>>] [$<I<file> ...>]

=head1 DESCRIPTION

B<dh_fortran_mod> is a debhelper program that finds Fortran module files and 
adds dependencies to B<gfortran-mod-$version> as required to the package using
via the variable B<${misc:Depends}>.

B<dh_fortran_mod> is expected to be automatically added using the debhelper "addon" B<fortran_mod>
ie. using the debian/rules line:

    dh $@ --with fortran_mod

Typically Fortran module files are included in library development packages.

-head1 TODO

B<dh_fortran_mod> will be expanded to find mod files automatically from the I<debian/tmp> directory.
It will enable the installation of mod files in parallel for multiple compilers.
It will check that mod files are installed in the correct location when multi-arch is enabled.
It will install .smod files for Fortran 2018.

=cut
    

# Default for now: gfortran only
my $multicompiler = 0; 
my $multiarch = 0;

our %modversions = ();

init(options => {
    'multicompiler' => \$multicompiler,
    'multiarch' => \$multiarch,
});



sub ScanDirectory{
    my ($workdir) = shift;
    chdir($workdir) or die "Unable to enter dir $workdir:$!\n";
    opendir(DIR, ".") or die "Unable to open $workdir:$!\n";
    my @names = readdir(DIR) or die "Unable to read $workdir:$!\n";
    closedir(DIR);

    foreach my $name (@names){
        next if ($name eq "."); 
        next if ($name eq "..");

        if (-d $name){                  # is this a directory?
            #Whatever you want to do goes here.
        }
    }
}



sub determine_mod_version {
    my $modfile = shift;
    my $magic = File::LibMagic->new();
    
    if ( ! (-r $modfile) ) {  
	warning("Can't open $modfile");
	return ('none', -1);
    }
    my ($mime) = split(/;/, $magic->checktype_filename($modfile));

    if ($mime eq "text/plain") {
        if ( ! (open(MODFILE, "<", $modfile))) {
	    warning($!);
	    return ('none', -1);
	}	     
        $_ = <MODFILE>;
        close(MODFILE);
    } elsif ($mime eq "application/gzip") {
        my $z = new IO::Uncompress::Gunzip $modfile or error("gunzip failed: $GunzipError\n");
        $_ = <$z>;
        $z->close();
    } else {
        print("wrong MIME type $mime for $modfile; ignoring");
	return ('none', -1);
    }

    if (/^GFORTRAN module version '([0-9]+)'/) {
        return ('gfortran', $1);
    } else {
        # error("$modfile is not a gfortran mod file.");
	return ('none', -1);
    }
}

# Should we install the .mod file in a Multi-arch aware directory for this package ?
# TODO: Write this
sub do_multiarch {
    my $package = shift;
    if ($multiarch) {
	return dpkg_architecture_value("DEB_HOST_MULTIARCH");
    } else { 
	return "";
    } 
}

foreach my $package (getpackages()) {
    next if is_udeb($package);

    my $tmpd = tmpdir($package);
    my $config = pkgfile($package, "fortran-mod");
    my $archd = do_multiarch($package);
    my $modfile;
    my $modd = '';
    my @install;
        
    # try parsing a list of files
    if ($config ne "") { 
	@install = filedoublearray($config);
	foreach my $set (@install) {
	    
	    my @tmp = @$set;
	    $modfile = $tmp[0];
	    my ($compiler, $modversion) = determine_mod_version($modfile);
	    
	    if ($compiler ne 'none') { 
		verbose_print ("Fortran modfile  $modfile created by $compiler modversion $modversion");
		
		if (@$set > 1) {
		    $modd = pop @$set;
		    $modd = "$tmpd/$modd";
		}
		else {
		    if ($multicompiler) {
			$modd = "$tmpd/usr/include/$archd/$compiler/$modversion/";
		    } else {
			$modd = "$tmpd/usr/include/$archd";
		    }
		}	
		verbose_print "installing $modfile into $modd";
		
		if (! -d "$modd") {
		    doit("install", "-d", "$modd");
		}
		
		if (!exists($modversions{$modversion})) {
		    $modversions{$modversion} = 1;
		    addsubstvar($package, "misc:Depends", "$compiler-mod-$modversion");
		    doit("install","-d",$modd);
		}
		doit("install",$modfile,$modd);
	    }
	}
    }
}


if (%modversions > 1) { 
    warning("Multiple compilers / compiler versions in file");
}


=head1 SEE ALSO

L<debhelper(7)>

=head1 AUTHORS

Sébastien Villemot <sebastien@debian.org>
Alastair McKinstry <mckinstry@debian.org>

=cut
