#!/usr/bin/perl -w
#
# Registration with wordlists

use strict;

my $class = "wordlist";
my $no_pre_post;
my $no_config;
my $debug;
#
#
my $write_elanguages;
my $no_installdebconf;

# -------------------------------------------------------
sub parse_options {
# -------------------------------------------------------
# Parse given options and remove them from the input list
# -------------------------------------------------------
  my @params = ();
  foreach ( @_ ){
    if ( $_ eq "--no-elanguages" ){
      $write_elanguages = '';
    } elsif ( $_ eq "--no-installdebconf" ){
      $no_installdebconf = 1;
    } elsif ( $_ eq "--no-pre-post" ){
      $no_pre_post = 1;
    } elsif ( $_ eq "--write-elanguages" ){
      $write_elanguages = 1;
    } elsif ( $_ eq "--debug" ){
      $debug++;
    } else {
      push @params, $_;
    }
  }
  return @params;
}

# -------------------------------------------------------
sub handle_debconf {
# -------------------------------------------------------
# Handle debconf stuff
# -------------------------------------------------------
  my $package = shift;
  my $dicts   = shift;

  return if $no_config;

  my $dictdir = "/usr/share/dictionaries-common/debconf";
  my $debug   = 1 if exists $ENV{'DICT_COMMON_DEBUG'};

  my $orig_config_file;
  my $orig_templates_file;
  my $orig_templates_txt;

  # Check and trigger an error if debian/[package].{config,templates} exist
  # -----------------------------------------------------------------------

  if (pkgfile ($package, "config")) {
    mydie ("debian/[package.]config file exists.  You should probably move
it to debian/[package.]config.in", "installdeb-$class(1)");
  }
  if (pkgfile ($package, "templates")) {
    mydie ("debian/[package.]templates file exists.  You should probably move
it to debian/[package.]templates.in", "installdeb-$class(1)");
  }

  # We are okay.  Generate the config file
  # -----------------------------------------------------------------------

  open (CONFIG, "> debian/$package.config");

  # Get the dictionaries-common Policy compliant config code
  my $config_dc = `cat $dictdir/config-$class`;

  # Check if there is a debian/[package.]config.in file
  if ($orig_config_file = pkgfile ($package, "config.in")) {
    my $isshell;
    # Read it and check if it is a Bourne shell or a Perl script
    open (INCONFIG, "< $orig_config_file");
    if ((my $shell_line = <INCONFIG>) =~ m{^\#!\s*(/bin/sh|/usr/bin/perl)}){
      $isshell = ($1 eq "/bin/sh");
    } else {
      mydie ("The $orig_config_file file must be either a shell or Perl script.",
	     "installdeb-$class(1)");
    }
    close INCONFIG;

    # Okay, look now for a the valid #DEBHELPER# string
    my $config_in;
    unless (($config_in = `cat $orig_config_file`) =~ /\n\#DEBHELPER\#\s*\n/) {
      mydie ("No valid #DEBHELPER# string in $orig_config_file. Aborting.",
	     "installdeb-$class(1)");
    }

    # The valid #DEBHELPER# string was found, so replace it by the
    # Policy specified code, taking care if it is a Bourne shell or
    # Perl script.
    if ($isshell) {
      $config_dc = qq(tmp=`tempfile`
cat > \$tmp <<EOF
$config_dc
EOF
perl \$tmp
rm -f \$tmp
);
    }
    $config_in =~ s/\#DEBHELPER\#/$config_dc/;
    # Save the whole thing in the config file
    print CONFIG $config_in;
  } else {
    # Put the Policy compliant code in creating a Perl script
    print CONFIG "#!/usr/bin/perl -w\n$config_dc";
  }
  close CONFIG;

  # Generate the templates file
  # -----------------------------------------------------------------------

  my @tmp_languages  = ();
  my @tmp_elanguages = ();
  my @tmp_defaults   = ();
  my $has_elanguages;

  foreach (keys %{$dicts}){
    my $lang  = $dicts->{$_};
    unless ( defined $lang->{'debconf-display'} &&  lc($lang->{'debconf-display'}) eq "no" ) {
      push (@tmp_languages,$_);
      if ( defined $lang->{'elanguage'} ){
	push (@tmp_elanguages,$lang->{'elanguage'});
	$has_elanguages++;
      } else {
	push (@tmp_elanguages,$_);
      }
    }
    if ( defined $lang->{'debconf-default'}
	 &&  lc($lang->{'debconf-default'}) eq "yes"){
      push (@tmp_defaults,$_);
    }
  }

  my $languages     = join (', ', @tmp_languages);
  my $elanguages    = join (', ', @tmp_elanguages);
  my $templates_txt = `cat $dictdir/templates-$class`;

  $templates_txt =~ s/\#LANGUAGES\#/$languages/;
  $templates_txt =~ s/\#PACKAGE\#/$package/g;

  # Do we have local templates to be added to the dict-common stuff?
  if ($orig_templates_file = pkgfile ($package, "po-master.templates")) {
    $orig_templates_txt = `cat $orig_templates_file`;
  } elsif ($orig_templates_file = pkgfile ($package, "templates.in")) {
    print STDERR " ** Warning: $orig_templates_file use is deprecated.\n" .
      "      Please base your template localization in po-debconf\n";
    $orig_templates_txt = `cat $orig_templates_file`;
  }

  if ($orig_templates_txt){
    $orig_templates_txt =~ s/^[\s\n]+//;
    $orig_templates_txt =~ s/[\s\n]+$//;
    $templates_txt .= "\n$orig_templates_txt\n";
  }

  # Add elanguages stuff
  if ( $write_elanguages or $has_elanguages ){
    # po-debconf will only process "^__" if "debian/po" dir is present
    my $translate_default_elanguage = ( -d "debian/po" ) ? "__" : "";
    $templates_txt .="
Template: $package/elanguages
Type: text
$translate_default_elanguage" . "Default: $elanguages
Description:
";
  }

  # Add template for defaults if present
  if ( scalar(@tmp_defaults) > 0 ){
    my $the_defaults = join (', ', @tmp_defaults);
    $templates_txt .= "
Template: $package/defaults
Type: text
Default: $the_defaults
Description:
";
  }

  open (TEMPLATES, "> debian/$package.templates");
  print TEMPLATES $templates_txt;
  close TEMPLATES;

  # Call dh_installdebconf  and do the clean up
  # -----------------------------------------------------------------------

  unless ( $no_installdebconf ){
    doit ("dh_installdebconf", "-p$package");
    doit ("rm", "-f", "debian/$package.config", "debian/$package.templates");
  }
}

##

# -------------------------------------------------------
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;

# ------ Steal own options before debhelper is initialized
@ARGV = &parse_options ( @ARGV );
#

use Debian::Debhelper::Dh_Lib;
init();

use Debian::DictionariesCommon q(:all);

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 $infofile;

  # Process the debian/info-wordlist 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-wordlist 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");

  # 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 "installdeb-$class: 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 "installdeb-$class 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 ( 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 $varlibrm     = "$auto_compats $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/");

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

	# Automatically provide symlinks for the different hashes
	my $usr_lib_dir = tmpdir($package) . "/usr/lib/$class";
	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 "installdeb-$class: Setting \"$usr_lib_dir/$hash\" symlink.\n" if $debug;
	    symlink "/var/lib/$class/$hash", "$usr_lib_dir/$hash"
	  }
	}
      }
    }
    autoscript ($package, "postinst", "postinst-$class",
		"s/#PACKAGE#/$package/");
    autoscript ($package, "postrm", "postrm-$class",
		"s/#PACKAGE#/$package/");
  }
  # -- Handle debconf stuff for this package
  &handle_debconf($package,$dicts);
  #
}


__END__

=head1 NAME

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

=head1 SYNOPSIS

 installdeb-wordlist [debhelper options] [options]

=head1 DESCRIPTION

B<installdeb-wordlist> is a debhelper like program that is
responsible for installing appropriate debconf config and templates
files and debhelper snippets in
a wordlist 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-wordlist> are the
following:

=over

=item * Maintainer Scripts

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

=item * Language info file

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

=item * Debconf files

=over

=item o templates and config files

B<installdeb-wordlist> installs the Policy compliant
Debconf files from the information contained in the
F<info-wordlist> file.  These files are created as
F<debian/config> (or F<debian/package.config>) and F<debian/templates>
(or F<debian/package.templates>).  No intervention is needed here,
since B<installdeb-wordlist> will make a call to
dh_installdebconf(1).

If the package needs to have special code in the F<config> file, the maintainer
should supply files called F<debian/config.in> (or
F<debian/package.config.in>). In the F<config.in> file, the string
C<#DEBHELPER#> must appear alone in one line and start at the first
column.  B<installdeb-wordlist> will replace that
token with the necessary Policy compliant code (this works with
F<config.in> is either a Bourne shell or Perl script).

If the package needs to define its own questions via the F<templates>
file the maintainer should either supply files F<debian/po-master.templates>
(or F<debian/package.po-master.templates>) together with the appropriate
po files if the package handles template localization through po-debconf,
or F<debian/templates.in> (or F<debian/package.templates.in>) otherwise.
See the po-debconf(7) manual page for more details and remember that the
master templates name is now different.

The templates defined in the F<templates.in> or F<po-master.templates> files
are merged into the Policy compliant templates by
installdeb-wordlist and a call to dh_installdebconf(1)
is internally done.

=item o The elanguages template field

This field is useful if you want to override the debconf languages string
with something different (since the master string remains the same, this
will not trigger a new debconf call) or if you really think that the
languages string should be internationalized for your package. Note that
for most packages the poor man default localization should be enough, and
translators should have another priorities.

installdeb-wordlist default behavior is not adding an
C<elanguages> field to the templates file. If you want it added you have
to call the script with the explicit B<--write-elanguages> option.

This field will be added with value taken from the C<Elanguage> entry in
the info file if present, or after the C<Language> value otherwise. Note
that this is useful only if:

=over

=item - You want to fix a buggy entry

In this case just fill the C<Elanguage> field in the info file with the
new value. This will be shown at the debconf prompt.

=item - You want to fully internationalize your entries

In this case some black magic is needed at first time for smooth use,

=over

=item (a) Run B<installdeb-{ispell,wordlist} --no-installdebconf --write-elanguages> for
      every package whose string should be internationalized. Edit the
      created F<.templates> files and remove the leading underscores in
      the elanguages entry if present.

=item (b) Run B<debconf-gettextize templates_to_be_internationalized>.
      Check that all the desired F<.templates> files are in
      F<debian/po/POTFILES.in> and remove old F<.config> and
      F<.templates> files.

=item (c) Run again B<installdeb-{ispell,wordlist} --no-installdebconf --write-elanguages> and
      B<debconf-updatepo> (no edit here) to remove references to
      non-translatable strings. Check that the desired strings are in the po
      master file (F<debian/po/templates.pot>) and remove F<.config> and
      F<.templates> files. You are done. If the master C<Elanguages> string
      is changed, repeat (c) afterward.

=back

=back

=back



=back

=head1 OPTIONS

The usual dephelper(1) options are accepted. Options below are specific
to B<installdeb-wordlist>

=over

=item B<--no-installdebconf>

Do not run B<dh_installdebconf> nor remove templates and config file.

=item B<--no-pre-post>

Do not install {pre,post}{inst,rm} snippets.

=item B<--write-elanguages>

Create the elanguages stuff.

=item B<--debug>

Show some extra info.

=back


=head1 NOTES

This program is not part of debhelper, although it is intended to be used
in wordlist 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
wordlist
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
