#! /usr/bin/perl
# gen_contents_index, written for Debian by Kari Pahula
# Copyright 2009 Kari Pahula
# Licensed under BSD3, see /usr/share/common-licenses/BSD

my @ifaces;
my %pkgs;

# Only do something if we actually have /usr/share/doc
exit 0 unless (-d "/usr/share/doc/ghc-doc/html/libraries/" and -r "/usr/share/doc/ghc-doc/html/libraries/prologue.txt");

# Add everything from the global Cabal registry to index.
if (-e '/usr/bin/ghc-pkg') {
    open CABAL, "/usr/bin/ghc-pkg --global --simple-output field '*' name,version,haddock-interfaces,haddock-html |" or warn "ghc-pkg dump failed: $!";
    addInfo (\*CABAL, \%pkgs, \@ifaces);
    close CABAL;
}

exec ('haddock', '--gen-index', '--gen-contents',
      '--mathjax', 'file:///usr/share/javascript/mathjax/MathJax.js',
      '-o', '/usr/share/doc/ghc-doc/html/libraries/',
      '-t'. 'Haskell Hierarchical Libraries',
      '-p', '/usr/share/doc/ghc-doc/html/libraries/prologue.txt',
      @ifaces);

sub addInfo {
    my $fh = shift;
    while (<$fh>) {
        my %dat;
        chomp ($dat{pkg} = $_);
        chomp ($dat{ver} = <$fh>);
        chomp ($dat{ifaces} = <$fh>);
        chomp ($dat{html} = <$fh>);
        process(\%dat, @_);
    }
}

sub process {
    my $dat = shift;
    my $pkgs = shift;
    my $ifaces = shift;
    my $path;
    return undef if $$dat{pkg} eq 'ghc';
    my $p = $$dat{pkg}.'-'.$$dat{ver};
    return undef if (exists $$pkgs{$p});
    if ($$dat{html} =~ m,^/usr/share/doc/ghc-doc/html/libraries/(.*),) {
        $path = $1;
    } elsif ($$dat{html} =~ m,^/usr/share/doc/([^/]*-doc/html/.*),) {
        $path = "../../../$1";
    }

    if (defined $path && -r $$dat{ifaces}) {
        $$pkgs{$p} = 1;
        push @ifaces, "--read-interface=$path,$$dat{ifaces}";
    }
}
