#!/usr/bin/perl -w

use strict;
use feature "switch";

my $lib_dir = "/usr/lib/emacsen-common";
my $invoked_by_old_pkg;
my $context;
my $flavor;

require $lib_dir . "/lib.pl";

umask 0022 or die "emacs-install: can't set umask, aborting.";

sub usage
{
  my($file_handle) = @_;
  if($invoked_by_old_pkg)
  {
    print $file_handle "Usage: emacs-install FLAVOR\n";
  }
  else
  {
    print $file_handle "Usage: emacs-install (--preinst|--postinst) FLAVOR\n";
  }
}

if(scalar(@ARGV) == 1)
{
  $invoked_by_old_pkg = 1;
  $flavor = $ARGV[0];
  $context = 'postinst;'
}
elsif (scalar(@ARGV) == 2)
{
  given($ARGV[0])
  {
    when('--preinst') { $context = 'preinst'; }
    when('--postinst') { $context = 'postinst'; }
    default
    {
      usage(*STDERR{IO});
      exit(1);
    }
  }
  $flavor = $ARGV[1];
}
else
{
  usage(*STDERR{IO});
  exit(1);  
}

# Let emacs-package-install/remove know what's going on.
$ENV{'CURRENTLY_HANDLING_EMACSEN'} = "Yes";

if($context eq 'preinst')
{
  unlink("$::installed_flavor_state_dir/$flavor");
  exit(0);
}

# Must be --postinst.

my @ordered_pkg_list =
    generate_add_on_install_list(get_installed_add_on_packages());

if(!$invoked_by_old_pkg)
{
  foreach my $pkg (@ordered_pkg_list)
  {
    print "Install $pkg for $flavor\n";
    my $script = $lib_dir . "/packages/install/$pkg";
    ex($script, $flavor) if -e $script;
  }
}
else # $invoked_by_old_pkg
{
  my $installed_flavors_ref = get_installed_flavors();
  my @installed_flavors = @$installed_flavors_ref;
  foreach my $pkg (@ordered_pkg_list)
  {
    print "Install $pkg for $flavor\n";
    my $script = $lib_dir . "/packages/install/$pkg";
    ex($script, $flavor, @installed_flavors) if -e $script;
  }
}

ex('touch', "$::installed_flavor_state_dir/$flavor");
