#! /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 $pkgdir = '/usr/share/ghc6-doc/ghc-@VERSION@/desc/';
my @ifaces;
my %pkgs;

# First, add everything from the global Cabal registry to index.
if (-e '/usr/bin/ghc-pkg6') {
    open CABAL, 'ghc-pkg6 dump --global |' or warn "ghc-pkg dump failed: $!";
    addInfo (\*CABAL, \%pkgs, \@ifaces);
    close CABAL;
}

# Then, add -doc packages that aren't registered but have the
# corresponding data installed otherwise.
opendir PKGS, $pkgdir;
while ($_ = readdir PKGS) {
    next if /^[.]/;
    open DESC, $pkgdir.$_;
    addInfo(\*DESC, \%pkgs, \@ifaces);
    close DESC;
}
closedir PKGS;

exec ('haddock', '--gen-index', '--gen-contents',
      '-o', '/usr/share/doc/ghc6-doc/libraries/',
      '-t'. 'Haskell Hierarchical Libraries',
      '-p', '/usr/share/doc/ghc6-doc/libraries/prologue.txt',
      @ifaces);

sub addInfo {
    my $fh = shift;
    my %dat;
    while (<$fh>) {
	if (/^name: (.*)/) {
	    $dat{pkg} = $1;
	} elsif (/^version: (.*)/) {
	    $dat{ver} = $1;
	} elsif (/^haddock-interfaces: (.*)/) {
	    $dat{ifaces} = $1;
	} elsif (/^haddock-html: (.*)/) {
	    $dat{html} = $1;
	} elsif (/^---/) {
	    process(\%dat, @_);
	    %dat = ();
	}
    }
    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/([^/]*-doc/html/.*),) {
	$path = "../../$1";
    } elsif ($$dat{html} =~ m,^/usr/share/doc/ghc6-doc/libraries/(.*),) {
	$path = $1;
    }
    if (defined $path && -r $$dat{ifaces}) {
	$$pkgs{$p} = 1;
	push @ifaces, "--read-interface=$path,$$dat{ifaces}";
    }
}
