#!/usr/bin/perl -w

=head1 NAME

dh_makenetlibs - automatically create netlibs file

=cut

use strict;
use Debian::Debhelper::Dh_Lib;

=head1 SYNOPSIS

B<dh_makenetlibs> [S<I<debhelper options>>] [B<-r>] [B<-V>I<[dependancies]>] [B<-m>I<minversion>] [B<-l>I<nextincompatible>] [B<-X>I<item>]

=head1 DESCRIPTION

dh_makenetlibs is a debhelper program that automatically scans for
versioned .NET assemblies, and generates a netlibs file for the
libraries it finds.

By default, dh_makenetlibs scans the DLL files in the package
directories and writes the discovered compatibility data (major/minor,
build, token) to "netlibs" files int he appropriate packages.

However, if a file like debian/package.netlibs is found, this one will
be installed and no scanning is performed.

=head1 OPTIONS

=over 4

=item B<-V>, B<-V>I<dependancies>

=item B<--version-info>, B<--version-info=>I<dependancies>

By default, the netlibs file generated by this program does not make packages
depend on any particular version of the package containing the assembly.
It may be necessary for you to add some version dependancy
information to the netlibs file. If -V is specified with no dependancy
information, the current version of the package is plugged into a
dependancy that looks like "packagename (>= packageversion)". If -V is
specified with parameters, the parameters can be used to specify the exact
dependancy information needed (be sure to include the package name).

Beware of using -V without any parameters; this is a conservative setting
that always ensures that other packages' shared library dependencies are at
least as tight as they need to be, so that if the maintainer screws up then
they won't break. The flip side is that packages might end up with
dependencies that are too tight and so find it harder to be upgraded.

=item B<-m>I<minversion>

Like -V, but specifies only the version string, the package name comes
from the package that is actually processed. This option is more
flexible if you try to set a range of valid versions for different
assembly packages coming from one source package.

=item B<-l>I<nextincompatible>

Specifies the (expected) version of this package when the compatibility
to the current assemblies will break.

=item B<-r>

An experimental option to automaticaly guess the next incompatible
upstream version and insert them (like working with -l and -m options,
see above). Do not expect the guessed values to be always correct -
normally, the usualy assumed version string has the form
generation.major.minor where versions with changes in "minor" are
compatible and "major" versions break with compatibility.

=item B<-X>I<item>, B<--exclude=>I<item>

Exclude files that contain "item" anywhere in their filename or directory 
from being treated as shared libraries.

=back

=head1 EXAMPLES

 dh_makenetlibs

Assuming this is a package named libfoobar0.9x-cil, generates a netlibs file that
looks something like:
 libfoobar  1.0.2345.0_23a12f34  libfoobar0.9x-cil

 dh_makenetlibs -V

Assuming the current version of the package is 0.93-3, generates a netlibs
file that looks something like:
 libfoobar 1.0.2345.0_23a12f34 libfoobar0.9x-cil (>= 0.93-3)

 dh_makenetlibs -V 'libfoobar0.9x-cil (>= 0.92)'

Generates a netlibs file that looks something like:
  libfoobar 1.0.2345.0_23a12f34 libfoobar0.9x-cil (>= 0.92)

Assuming that your package creates libfoobar-cil and liblafasel-cil,
which are compatible to 0.92 versions but the upstream is going to break
compatibility in the next version, 0.94:

 dh_makenetlibs -m 0.92 -l 0.94

Generates netlibs file that looks something like:

  libfoobar 1.0.2345.0_23a12f34 libfoobar-cil (>= 0.92), libfoobar-cil (<< 0.94)

and

  liblafasel 1.0.2345.0_23a12f34 liblafasel-cil (>= 0.92), liblafasel-cil (<< 0.94)

=cut

init();

if ( system "grep -q \"Build-Dep.*mono-utils.*0.9\" debian/control" ) {
    warning("Warning! No Build-Depends on mono-utils (>= 0.96)!");
}

my $fh;
my %shlibdata;
sub extraDeps {
   my $config=$_[0].".config";
   my $ret=undef;

   if(!%shlibdata) {
      open( $fh, "cat /var/lib/dpkg/info/*.shlibs debian/shlibs.local debian/*/DEBIAN/shlibs 2>/dev/null |" );
      while (<$fh>) {
         /(\S+)\s+(\S+)\s+(\w.*)\n?/;
         $shlibdata{"$1.so.$2"} = $3;
      }
   }

   if( -r $config) {
      $config=`cat $config`;
      while($config=~s/\Wtarget\W*=\W*(\w[\w.\-\d]+)//) {
         $ret.= (", ".$shlibdata{$1}) if(defined($shlibdata{$1}));
      }
   }
   $ret=~s/^, // if $ret;
   return $ret;
}

foreach my $package ( @{ $dh{DOPACKAGES} } ) {
    next if is_udeb($package);

    my $tmp = tmpdir($package);

    my %seen;
    my $need_ldconfig = 0;

    doit( "rm", "-f", "$tmp/DEBIAN/netlibs" );
    if ( -e "debian/$package.netlibs" ) {
        complex_doit("cat debian/$package.netlibs >$tmp/DEBIAN/netlibs");
    }
    else {

        # So, we look for files or links to existing files with names that
        # match "*.so*". Matching *.so.* is not good enough because of
        # broken crap like db3. And we only look at real files not
        # symlinks, so we don't accidentually add netlibs data to -dev
        # packages. This may have a few false positives, which is ok,
        # because only if we can get a library name and a major number from
        # objdump is anything actually added.
        my $exclude = '';
        if ( defined( $dh{EXCLUDE_FIND} ) && $dh{EXCLUDE_FIND} ne '' ) {
            $exclude = "! \\( $dh{EXCLUDE_FIND} \\) ";
        }
        open( FIND, "find $tmp -type f \\( -name '*.dll' \\) $exclude |" );
        dll: while (<FIND>) {
            chomp;
            my ( $library, $ver, $libfile );
            $libfile = $_;
            my $sig = `sn -T $_ 2>/dev/null`;
            $sig =~ s/.*key token: (\w+).*/$1/is;
            if($sig=~/\s/) {
               warning "$libfile has no valid signature, ignoring";
               next dll;
            }
            my $dis = `monodis --assembly $libfile 2>&1`;
            if($dis =~ m/Name:\s+(\S+)/) {
               $library = $1;
               $dis =~ m/Version:\s+(\S+)/;
               $ver = $1;
            }
            else {
               # completely broken code, we need a mature app not
               # depending on assembly loading
               # verbose_print("trouble parsing monodis output, components not installed? Fallback to parsing the pure monodis output.");
               # $dis = `monodis $libfile 2>&1`;
               # $dis =~ /^module (\S+)/is;
               # $library = $1;
               # $library =~ s/'|"//;
               warning("monodis could not open $libfile, maybe some components not installed yet. Using filename to guess the assembly name :(");
               $libfile=~ m,/(\d+\.\d+.\d+.\d+)__(\w+)/([^/]+)\.dll$,is;
#               print "moo: $1, $2, $3";
               next dll if (! ($1 && $2 && $3));
               $ver=$1;
               $sig=$2;
               $library=$3;
            }

            if ( !-d "$tmp/DEBIAN" ) {
                doit( "install", "-d", "$tmp/DEBIAN" );
            }
            my $deps = $package;

            # Call isnative becuase it sets $dh{VERSION}
            # as a side effect.
            isnative($package);
            my $version = $dh{VERSION};

            # Old compatibility levels include the
            # debian revision, while new do not.
            if ( !compat(3) ) {

                # Remove debian version, if any.
                $version =~ s/-[^-]+$//;
            }

            if ( defined( $dh{M_PARAMS} ) && $dh{M_PARAMS} ne '' ) {
                $version = $dh{M_PARAMS};
            }
            if ( $dh{V_FLAG_SET} ) {
                if ( $dh{V_FLAG} ne '' ) {
                    $deps = $dh{V_FLAG};
                }
                else {
                    $deps = "$package (>= $version)";
                }
            }
            if ( defined( $dh{R_FLAG} ) ) {
                $version =~ s/-[^-]+$//;
                my @uvers = split ( /\./, $version );
                $uvers[1]++;
                $deps =
                  "$package (>= $version), $package (<< "
                  . join ( ".", @uvers ) . ")";
            }
            if ( defined( $dh{M_PARAMS} ) ) {
                $deps = "$package (>= " . $dh{M_PARAMS} . ")";
            }
            if ( defined( $dh{L_PARAMS} ) ) {
                $deps .= ", $package (<< " . $dh{L_PARAMS} . ")";
            }
            if ( defined($library)
                && defined($ver)
                && defined($deps)
                && $library ne ''
                && $ver ne ''
                && $deps ne '' )
            {

                # Prevent duplicate lines from entering the file.
                my $line = "$library $ver" . "__$sig $deps";

                # extra dependencies are to be resolved by dh_netlibs,
                # don't forward the dependency libs to the apps where it
                # does not belong to
#                if ( my $extra = extraDeps ($libfile) )   { $line .= ", $extra";  }
                if ( !$seen{$line} ) {
                    $seen{$line} = 1;
                    complex_doit("echo '$line' >>$tmp/DEBIAN/netlibs");
                }
            }
        }
    }
    close FIND;

    if ( -e "$tmp/DEBIAN/netlibs" ) {
        doit( "chmod", 644,   "$tmp/DEBIAN/netlibs" );
        doit( "chown", "0:0", "$tmp/DEBIAN/netlibs" );
    }
}

=head1 SEE ALSO

L<debhelper(7)>

This program is a part of mono-utils.

=head1 KNOWN BUGS

Will possibly not work correctly with DH_COMPAT levels 1 and 2.

=head1 AUTHOR

Eduard Bloch <blade@debian.org>, inspired by dh_makeshlibs by Joey Hess <joeyh@debian.org>

=cut

