#!/usr/bin/perl -w
#
# Registration with aspell dictionary

use strict;

my $class = "aspell";
my $program = "installdeb-$class";
my $no_pre_post;
my $no_config;
my $debug;
#

#
#

# -------------------------------------------------------
sub mydie {
# -------------------------------------------------------
  my $msg = shift;
  my $see = shift;
  die "$msg\nPlease see $see.\n";
}

# -------------------------------------------------------
sub mywarn {
# -------------------------------------------------------
  my $msg = shift;
  my $see = shift;
  warn "$msg\nPlease see $see.\n";
  exit 0;
}

# =======================================================
# Main part
# =======================================================

use Text::Wrap;
$Text::Wrap::columns = 72;

# --- No extra options for aspell 

use Debian::Debhelper::Dh_Lib;
use Debian::DictionariesCommon q(:all);

if ( $class eq "aspell" ){
  init(options => { 'aspell-simple' => \$dh{ASPELL_SIMPLE} });
} else {
  init();
}

if ( defined $dh{NOSCRIPTS} ){
  $no_pre_post = 1;
  $no_config   = 1;
};

$debug++ if ( defined $ENV{DICT_COMMON_DEBUG} );

foreach my $package (@{$dh{DOPACKAGES}}) {

  my $lib_dir       = tmpdir($package) . getlibdir($class);
  my $usr_lib_dir   = tmpdir($package) . "/usr/lib/$class";
  my $var_lib_dir   = tmpdir($package) . "/var/lib/$class";
  my $usr_share_dir = tmpdir($package) . "/usr/share/$class";
  my $infofile;

  # Process the debian/info-aspell file
  unless ( $infofile = pkgfile ($package, "info-$class") ) {
    mywarn ("There is no debian/[package.]info-$class file for package $package.",
            "the dictionaries-common Policy");
  }

  # Parse the debian/info-aspell file
  my $dicts = parseinfo ($infofile);

  # If we get here, the parseinfo call was successful. Install the
  # file in the dictionaries-common lib dir.
  doit ("install", "-d", $lib_dir);
  doit ("install", "-m644", $infofile, "$lib_dir/$package");

  #
  my %dico_aspell_simple = ();
  # If $dh{ASPELL_SIMPLE} is enabled, make install from aspell dict should have been run
  # Get its info from installed .rws and .dat, install .cwl after it and try guesing
  # correct values for auto-compat and auto-hash
  if ( $dh{ASPELL_SIMPLE} ){
    # Parse Makefile.pre to extract .dat and .compat file names after lang info
    if ( -f "Makefile.pre" ){
      open (my $MAKEFILEPRE, "<Makefile.pre");
      while (<$MAKEFILEPRE>){
	chomp;
	if ( s/^lang\s+=\s+// ){
	  s/\s+$//;
	  my $dat = "$_.dat";
	  if ( $_ && -e "$dat" ){
	    $dico_aspell_simple{'lang'}= $_;
	  } else {
	    error("Malformed aspell dict: \$lang.dat file \"$dat\" not found.");
	  }
	  last;
	}
      }
      close $MAKEFILEPRE;
      error("No \$lang found in Makefile.pre.")
	unless ( defined $dico_aspell_simple{'lang'} );
    } else {
      error("\"Makefile.pre\" not found. --aspell-simple works only with pristine aspell dicts created with proc utility. See dh_aspell-simple(1) for more info.");
    }

    # Parse rws files. Should be a matching .cwl file for each one.
    my @rwsfiles = map {basename $_} glob("$usr_lib_dir/*.rws");
    doit ("install", "-d", $usr_share_dir) if (scalar @rwsfiles );
    foreach my $rws ( @rwsfiles ){
      my $base = $rws;
      $base =~ s/\.rws$//;
      my $cwl = "$base.cwl";
      if ( -e "$cwl" ){
	doit ("install","-m644","$cwl","$usr_share_dir");
	doit ("gzip", "-9nf", "$usr_share_dir/$cwl");
	$dico_aspell_simple{'auto-hash'}{$base}++;
      } else {
	warning("$program: No \"$cwl\" found for matching \"$rws\".");
      }
      verbose_print("Erasing $usr_lib_dir/$rws");
      doit ("rm", "-f", "$usr_lib_dir/$rws") unless ( -l "$usr_lib_dir/$rws" );
    }

    # Check if we need a contents file. Other sanity checks.
    if ( scalar keys %{$dico_aspell_simple{'auto-hash'}} == 0 ){
      error("No installed .rws hashes found for this aspell dictionary.");
    } else {
      my $tmp_dat = $dico_aspell_simple{'lang'};
      if ( scalar keys %{$dico_aspell_simple{'auto-hash'}} == 1 ){
	my $tmp_hash = (keys %{$dico_aspell_simple{'auto-hash'}})[0];
	if ( "$tmp_hash" ne "$tmp_dat" ){
	  error("$program: Not matching \"$tmp_dat.dat\" and \"$tmp_hash.rws\".");
	}
      } else {
	$dico_aspell_simple{'auto-contents'} = $tmp_dat;
      }
    }
  }
  # 

  # Install debhelper and debhelper-like auto-scripts
  unless ( $dh{NOSCRIPTS} or $no_pre_post) {
    if ( $class ne "wordlist" ){
      my %hash_extension      = ("ispell" => "hash", "aspell" => "rws");
      my %auto_hash_basenames = ();
      my %auto_extra_hash_basenames = ();

      # Get list of basenames for compat and contents files
      my %auto_compat_basenames   = ();
      my %auto_contents_basenames = ();
      foreach my $language ( keys %$dicts ){
	my $entry  = $dicts->{$language};
	if ( defined $entry->{'auto-compat'} ) {
	  my $compat = $entry->{'auto-compat'};
	  foreach ( split(" ", $compat) ){
	    s/\.compat$//;
	    $auto_compat_basenames{$_}++;
	  }
	}
	if ( defined $entry->{'auto-contents'} ) {
	  my $contents = $entry->{'auto-contents'};
	  foreach ( split(" ", $contents) ){
	    s/\.contents$//;
	    $auto_contents_basenames{$_}++;
	  }
	}
	# Hashes list should be created automatically. This is here to
	# add an extra hash name to the clean list on package
	# removal. If you think about this, you may prefer to
	# unconditionally remove old file from maintainer scripts.
	if ( defined $entry->{'auto-extra-hash'} ) {
	  my $extra_hashes = $entry->{'auto-extra-hash'};
	  foreach ( split(" ", $extra_hashes) ){
	    s/\.$hash_extension{$class}$//;
	    $auto_hash_basenames{$_}++;
	    $auto_extra_hash_basenames{$_}++;
	  }
	}
      }

      # Get automatic list of basenames for different hashes
      foreach my $base_name ( sort keys %auto_compat_basenames ){
	my $contents_file;
	if ( $class eq "aspell" ) {
	  # Check if there is an associated contents file.
	  my $tmp_contents_file = "debian/$base_name.contents";
	  if ( -e $tmp_contents_file ) {
	    print STDERR "installeb-$class: Found contents file \"$tmp_contents_file\".\n"
	      if $debug;
	    # and if it has been declared.
	    if ( defined $auto_contents_basenames{$base_name} ){
	      print STDERR "installeb-$class: contents file \"$tmp_contents_file\" is properly declared.\n"
		if $debug;
	      $contents_file = $tmp_contents_file;
	    } else {
	      print STDERR "$program: Warning:\n"
		. "\"$tmp_contents_file\" found, but no associated 'auto-compat' entry in info file.\n"
		. "Ignoring \"$tmp_contents_file\"...\n";
	    }
	  } elsif ( defined $auto_contents_basenames{$base_name} ){
	    die "$program error: No matching \"$tmp_contents_file\" for 'auto-compat' entry \"$base_name\". Aborting ...\n";
	  }
	}
	# Parse aspell contents file if enabled and present.
	if ( $contents_file ){
	  open (my $CONTENTS, "< $contents_file")
	    or die "Could not open contents file \"$contents_file\". Aborting ...";
	  while (<$CONTENTS>){
	    next if m /^\s*\#/;
	    next if m/^\s*$/;
	    chomp;
	    s/\.rws$//;
	    # Add contents info to list of hashes to be removed.
	    $auto_hash_basenames{$_}++;
	  }
	  close $CONTENTS;
	} else {
	  # Add base name to list of hashes to be removed.
	  $auto_hash_basenames{$base_name}++;
	}
      }

      #
      if ( $dh{ASPELL_SIMPLE}
	   && ! %auto_compat_basenames
	   && defined $dico_aspell_simple{'lang'} ){
	if ( defined $dico_aspell_simple{'auto-contents'} ){
	  my $contents = join(" ",sort keys %{$dico_aspell_simple{'auto-hash'}});
	  complex_doit("echo $contents | tr -s ' ' '\n' > $usr_share_dir/$dico_aspell_simple{'auto-contents'}.contents");
	  $auto_compat_basenames{$dico_aspell_simple{'auto-contents'}}++;
	  $auto_hash_basenames{$_}++ foreach keys %{$dico_aspell_simple{'auto-hash'}};
	} else {
	  my $hash_basename =  (keys %{$dico_aspell_simple{'auto-hash'}})[0];
	  $auto_compat_basenames{$hash_basename}++;
	  $auto_hash_basenames{$hash_basename}++;
	}
      }
      #

      if ( scalar %auto_compat_basenames && $debug ){
	print STDERR "installeb-$class info:\n";
	if ( %auto_contents_basenames ){
	  print STDERR " auto-contents: \"",join(', ',sort keys %auto_contents_basenames),"\"\n";
	}
	print STDERR " auto-compat: \"",join(', ',sort keys %auto_compat_basenames),"\"\n";
	print STDERR " auto-hash: \"",  join(', ',sort keys %auto_hash_basenames), "\"\n";
      }

      if ( scalar %auto_compat_basenames ){
	my $auto_compats  = join(" ", map { $_ . ".compat" } sort keys %auto_compat_basenames);
	my $auto_hashes   = join(" ", map { $_ . ".$hash_extension{$class}" } sort keys %auto_hash_basenames);
	my $varlibrmfiles = join(" ", map { $_ . ".remove" } sort keys %auto_compat_basenames);
	my $varlibrm      = "$auto_compats $varlibrmfiles $auto_hashes";

	# Install extra auto-scripts for auto-compat handling
	autoscript ($package, "preinst", "preinst-compatfile-$class",
		    "s/#COMPAT#/$auto_compats/");
	autoscript ($package, "postinst", "postinst-compatfile-$class",
		    "s/#COMPAT#/$auto_compats/");
	autoscript ($package, "postrm", "postrm-varlibrm-$class",
		    "s/#VARLIBRM#/$varlibrm/;s/#VARLIBRMFILES#/$varlibrmfiles/");

	# Make sure /var/lib/{a,i}spell directory is available.
	doit ("install", "-d", $var_lib_dir);

	# Automatically provide symlinks for the different hashes
	doit ("install", "-d", $usr_lib_dir);
	foreach my $hash ( sort keys %auto_hash_basenames ){
	  # Not for extra hashes only for the clean list
	  next if ( defined $auto_extra_hash_basenames{$hash} );
	  $hash = $hash . '.' .$hash_extension{$class};
	  unless ( -e "$usr_lib_dir/$hash" ){
	    print STDERR "$program: Setting \"$usr_lib_dir/$hash\" symlink.\n" if $debug;
	    doit ("ln", "-sf", "/var/lib/$class/$hash", "$usr_lib_dir/$hash");
	  }
	}
      }
    }
    autoscript ($package, "postinst", "postinst-$class",
		"s/#PACKAGE#/$package/");
    autoscript ($package, "postrm", "postrm-$class",
		"s/#PACKAGE#/$package/");

    # Populate substvars $class:Depends
    if ( "$class" ne "wordlist" ){
      # aspell >= 0.60.3-3, satisfied in squeeze. ispell minimal version is also ancient.
      addsubstvar ($package, "$class:Depends", "$class");
      addsubstvar ($package, "$class:Depends", "dictionaries-common", ">= 1.10");
    } else {
      addsubstvar ($package, "$class:Depends", "dictionaries-common", ">= 1.0");
    }
  }
  # -- No debconf handling needed for aspell or hunspell --
}


__END__

=head1 NAME

B<installdeb-aspell> - debhelper-like utility for
maintainers of aspell dictionary Debian packages

=head1 SYNOPSIS

 installdeb-aspell [debhelper options] 

=head1 DESCRIPTION

B<installdeb-aspell> is a debhelper like program that is
responsible for installing appropriate debhelper snippets in
an aspell dictionary package,
according to the Debian Spell Dictionaries and Tools Policy.

For more details, see
 /usr/share/doc/dictionaries-common-dev/dsdt-policy.txt.gz

The actions executed by B<installdeb-aspell> are the
following:

=over

=item * Maintainer Scripts

B<installdeb-aspell> installs the necessary
scraps of code in the F<postinst> and F<postrm> scripts.

=item * Language info file

B<installdeb-aspell> also checks a file containing
aspell dictionary information, called
F<debian/info-aspell> or
F<debian/package.info-aspell>.  If this file is
successfully parsed, it is installed in the
F</var/lib/dictionaries-common/aspell> directory.

=item * Debconf files

As opposed to B<installdeb-ispell> and B<installdeb-wordlist>, neither B<installdeb-aspell>
nor B<installdeb-hunspell> do anything related to debconf files, since both aspell and
hunspell rely on the environment variable C<LANG> for default dictionary selection
instead of using symlinks set after a debconf question on dictionary
installation. For that reason if you need to add debconf stuff with debhelper
to your aspell or hunspell dictionary package do it in the usual way and call
dh_installdebconf(1) as for any other package.


=item * Extra installdeb-aspell options in Language info file

For benefit of aspell dictionaries using B<aspell-autobuildhash>,
B<installdeb-aspell> script will look for C<'auto-compat'> and
C<'auto-contents'> fields in F<$lang.info-aspell>, containing base
name(s) of your compat and, if needed, contents file(s).  If
C<'auto-compat'> entry is found two debhelper snippets are added, one
to create/reset compatfile(s) in postinst and the other to remove
files in a removal list (initially containing compat files) from
postrm.  If C<'auto-contents'> entry is found, contents file at
F<debian/> will be parsed and its contents added to the removal list,
otherwise a hash with the same basename of the compatfile is expected
and added to the removal list.  Unless previous stuff exists,
F</usr/lib/aspell}/$dict.rws -E<gt> /var/lib/aspell/$dict.rws>
symlinks will also be automatically created.  If you use a contents
file and enable it in C<'auto-contents'> you usually will need only
the same base name enabled in C<'auto-compat'>.

If you are interested in a simple install of a pristine aspell
dictionary with a minimal debian/rules please look at
L<dh_aspell-simple(1)>.
You will still need an aspell-info file, but compat/contents stuff
will be guessed if not explicitly provided in the aspell-info file.



=back

=head1 OPTIONS

The usual dephelper(1) options are accepted. 

=head1 NOTES

This program is not part of debhelper, although it is intended to be used
in aspell dictionary packages using debhelper in its
building.

=head1 SEE ALSO

debhelper(1)

This program is part of the dictionaries-common-dev package. It is
intended to be used by maintainers of
aspell dictionary
packages for Debian. See the documentation
under /usr/share/doc/dictionaries-common-dev.

=head1 AUTHORS

Rafael Laboissiere, Agustin Martin

=cut

# Local Variables:
#  mode: perl
#  mode: flyspell-prog
#  ispell-local-dictionary: "american"
# End:

#  LocalWords:  aspell ispell wordlist debconf debhelper Debian config postrm
#  LocalWords:  debian elanguages installdeb dephelper installdebconf Elanguage
#  LocalWords:  Laboissiere
