#!/usr/bin/perl -w

use Debian::DictionariesCommon q(:all);
use Debconf::Client::ConfModule q(:all);
use Getopt::Long;

die "$0: You must run this as root.\n" if ($> != 0);

my $rebuild = '';
my $ignoresymlinks = '';

GetOptions ('rebuild' => \$rebuild,
	    'ignore-symlinks' => \$ignoresymlinks);

version ('2.0');

my $class     = "ispell";
my $libdir    = "/usr/lib/ispell";
my $question  = "dictionaries-common/default-$class";
my $iquestion = "dictionaries-common/invalid_debconf_value";
my $linkdir   = "/etc/dictionaries-common";
my $manual    = '';
my $emacsen_default = "nil";
my $cache_dir = "/var/cache/dictionaries-common";
my $emacsen_default_file = "$cache_dir/emacsen-ispell-default.el";
my $ispell_dicts_list = "$cache_dir/ispell-dicts-list.txt";

($ret, $value)  = get ($question);

if ($ret == 0 && $value ){
  
  updatedb ($class);
  my $dictionaries = loaddb ($class);
  
  if ( scalar(keys %{$dictionaries}) == 0 ){
    print STDERR "$0 No $class elements installed.\n";
    $value = "Manual forced (No $class elements installed)";
    set($question,$value);
    go();
  }
  
  if ( $value =~ m/^Manual.*/i ){       # Check if we are in manual mode
    $ignoresymlinks = "yes";
    $manual         = "yes";
  }

  if ( not $ignoresymlinks) {
    
    if (not exists $dictionaries->{$value}){         # Handle invalid debconf values
      my @available_keys=();
      foreach ( split (/\s*,\s*/, metaget ($question, "choices")) ){
	s/\s*(.*)\s*/$1/;          # strip possible leading/trailing whitespaces
	push (@available_keys,$_) if ( exists $dictionaries->{$_} );
      }
      my $choices = join (', ', sort {lc $a cmp lc $b} @available_keys);
      my $forced_key = $available_keys[0] ||
	  die "Selected ispell dictionary:\n" .
	  " $value \n" .
	  "does not correspond to any installed package in the system\n" .
	  "and no alternative ispell dictionary could be selected.\n";
      subst($iquestion,"value",$value);
      fset ($iquestion,"seen","false");
      input("high",$iquestion);               # Warn about what happened
      subst ($question, "choices", $choices); # Put sane values in debconf choices field
      set ($question, $forced_key);           # Set debconf value to a sane one  
      fset ($question,"seen","false");
      input ("critical", $question);  
      title ("dictionaries-common: ispell dictionaries");
      go ();
      ($ret, $value) = get ($question);
      die "\n Could not get a valid value for debconf question:\n" .
	  "$question\n"
          if ( $ret != 0 ); # This should never be reached
    }
    
    die "Selected ispell dictionary:\n" .
	" $value \n" .
	"does not contain a hash name entry in the database.\n"
	if (not exists $dictionaries->{$value}{"hash-name"});
 
    setsysdefault ($value); # This here is only for ispell, not wordlist

    my $hash   = "$libdir/" . $dictionaries->{$value}{"hash-name"};

    foreach my $i (".hash", ".aff") {

      die "
When trying to make the default link to a ispell dictionary
the file to link [$hash$i] was not found. Please report this as a bug to the
maintainer of the ispell dictionary package you tried to
select.
In the meantime select other default value for your ispell dictionary.\n"
if (not -e "$hash$i");
      
      system "ln -fs $hash$i $linkdir/default$i";
      
    }
  }
# Printing a plain list with installed ispell dictionaries,
  open (IDICTS,"> $ispell_dicts_list") || 
         die "Could not open $ispell_dicts_list for writing\n";
  foreach ( sort keys %{$dictionaries} ){
    print IDICTS "$_\n";
  }
  close (IDICTS);
  # Write ispell default dict for emacsen
  unless ( $manual ){
    if ( exists $dictionaries->{$value}{"emacs-display"} 
	 and lc($dictionaries->{$value}{"emacs-display"}) eq "no" ){  
      $emacsen_default = "nil";
    } elsif ( exists $dictionaries->{$value}{"emacsen-name"} ){
      $emacsen_default = "\"" . $dictionaries->{$value}{"emacsen-name"} . "\"";
    } elsif( exists $dictionaries->{$value}{"hash-name"} ){
      $emacsen_default = "\"" . $dictionaries->{$value}{"hash-name"} . "\"";
    }
  }
}

# Printing the default ispell dictionary under emacs
open (EMISDEFAULT,"> $emacsen_default_file");
print EMISDEFAULT ";; File automatically generated by update-default-ispell
;; 
;; Do not manually edit!! Use select-default-ispell script instead

(set-variable \'debian-ispell-dictionary $emacsen_default)\n";
close EMISDEFAULT;


if ($rebuild) {

  updatedb ($class);

  # Ispell emacsen + jed support
  build_emacsen_support ();
  build_jed_support ();
  system ("ispell-autobuildhash") == 0
      or die "Error running ispell-autobuildhash\n";
  # End of specific ispell support 
}

#Local Variables:
#perl-indent-level: 2
#End:

__END__

=head1 NAME

update-default-ispell - update default ispell dictionary 

=head1 SYNOPSIS

 update-default-ispell [--rebuild] [--ignore-symlinks]

=head1 DESCRIPTION

WARNING: Not to be used from the command line unless you know very well what you are doing. 

This program is intended to be called from package postinst 
(with B<--rebuild>), from B<select-default-ispell> or 
from dictionaries-common 
postinst (with B<--ignore-symlinks>).

Reads the system default from the debconf database and set default links in 
F</etc/dictionaries-common> pointing to the appropriate files in 
F</usr/lib/ispell/>.  Also 
updates the system-wide setting F</etc/dictionaries-common/ispell-default>.
If option B<--rebuild> is given, rebuilds the 
F</var/cache/dictionaries-common/ispell.db>  
and the emacsen and jed support (to be put in
F</var/cache/dictionaries-common/>) from the files in
F</var/lib/dictionaries-common/ispell>


=head1 OPTIONS

--rebuild          Rebuild database, emacsen and jed stuff
--ignore-symlinks  Do not set symlinks


=head1 SEE ALSO

The dictionaries-common policy document

=head1 AUTHORS

Rafael Laboissiere

=cut
