#!/usr/bin/perl -w

=head1 NAME

dh_installtexfonts - register Type 1 fonts with TeX

=cut

use strict;
use Debian::Debhelper::Dh_Lib;

=head1 SYNOPSIS

B<dh_installtexfonts> [S<I<debhelper options>>] [B<-n>] [B<--priority=>I<n>] 
    [B<--flavor=>I<flavor>] [S<I<maptype=mapfile ...>>] [S<I<cfg-file[=I<n>] ...>>] 

=head1 DESCRIPTION

dh_installtexfonts is a debhelper program that is responsible for
registering Type 1 fonts with TeX.

Your package should depend on tex-common so that the
update-* commands are available. (This program adds that dependency to
${misc:Depends}.)

Registering map files for TeX can be done in the following ways:

1) You can specify cfg files on the cmd line, optionally providing a 
priority by affixing =n to it. These cfg files will be 
installed into /etc/texmf/updmap.d/ with the specified priority, if present,
or with the default priority and their original name.

Example:

	dh_installtexfonts foo.cfg dvips/bar.cfg=42

would install foo.cfg as /etc/texmf/updmap.d/10foo.cfg, and dvips/bar.cfg
as /etc/texmf/updmap.d/42bar.cfg.

2) You can specify map lines on the cmdline, where the map type and the
map files is connected with =. These map lines are stored in a cfg file
10package.cfg.

Example:

	dh_installtexfonts Map=foo.map MixedMap=bar.map

would install a file /etc/texmf/updmap.d/10package.cfg containing the lines

	Map foo.map
	MixedMap bar.map

3) You create a file debian/package.maps or debian/maps. These files are
installed with default priority and the name of the package. The file 
debian/maps will be installed into the first package dh_installtexfonts 
is told to act on. By default this is the first binary package in 
debian/control, but if you use -p, -i, or -a flags, it will be the first
package specified by those flags.

Example:

	dh_installtexfonts

would install a present debian/package.maps file as 
/etc/texmf/updmap.d/10package.cfg.

=head2 Mixing the different variants

The command line maps (Variant 2) are merged into the debian/package.maps 
file and the merged file is installed as 10package.cfg. If you specify 
an additional package.cfg (Variant 1) without a different priority than
the default one on the cmd line, this will raise an error since both files 
would be installed as 10package.cfg. You can only specify package.cfg without
a different priority than the default one if no debian/package.maps nor
any command line Map files are present.

=head2 The pseudo-comment

If the provided cfg files do not contain the pseudo-comment as described
in the Debian TeX Policy, Font configuration, an additional header with
explanation, warning and the pseudo-comment is added.


This program automatically generates the postinst and postrm commands needed
to register the fonts with TeX.  See L<dh_installdeb(1)> for an explanation 
of how this works.

=head1 OPTIONS

=over 4

=item B<-n>, B<--noscripts>

Do not modify postinst/prerm scripts.

=item B<--priority=>I<n>

Set the default priority to I<n> instead of 10.

=item B<--flavor=>I<flavor>

This option will be used to switch additional options on. At the moment
you can select for I<flavor> either B<config_for_active_maps> or 
B<config_for_all_maps>.
B<config_for_active_maps> will create a file I<config.bar> for each active
(i.e. uncommented) map in each of the cfg file generated by one of the
three methods described above. These files are installed in
/usr/share/texmf/dvips/config/.

If you select B<config_for_all_maps> the script will generate I<config.bar>
even for those map files which are present in a cfg file, but deactivated by a comment.

The file I<config.bar> is used when called by `dvips -Pbar ...'. Thus it
allows the activation of single map files even if they are not automatically
activated via the updmap(-sys) mechanism.

Default is I<not> to generate any config files.

=head1 NOTES

Note that this command is not idempotent. "dh_clean -k" should be called
between invocations of this command, unless using the B<-n> option. 
Otherwise, it may cause multiple instances of the same text to be added 
to maintainer scripts.

Please refer to the Debian TeX policy for details about fonts configuration
for TeX by Debian packages.

=cut

init();

sub extract_map {
	my ($line,$doconfig) = @_;
	if ($doconfig == 0) { return ""; }
	if ($_ =~ m/^[[:space:]]*([#[:space:]]*)[[:space:]]*(Mixed)?Map[[:space:]]*(.*\.map)[[:space:]]*(#.*)?$/) {
		my $comment = $1;
		my $map = $3;
		if (($comment eq "") || ($doconfig == 2)) {
			return $map;
		}
	}
	return "";
}

sub magic_comment_present {
	my ($fname) = @_;
	my @args = ( "grep", "-q", "^# -_- DebPkgProvidedMaps -_-", $fname );
	if (system(@args) == 0) { return 1; }
	return 0;
}

my $magicheader = "# You can change/add entries to this file and changes will be preserved
# over upgrades, even if you have removed the main package prior
# (not if you purged it). You should leave the following pseudo comment
# present in the file!
# -_- DebPkgProvidedMaps -_-
#
";

foreach my $package (@{$dh{DOPACKAGES}}) {
	my $tmp=tmpdir($package);
	my $file=pkgfile($package,"maps");
	my $priority=10;
	my @pkgcfg;
	my @cmdlinemaps;
	my %cmdcfgshash;
	my @cmdlinecfgs;
	my $pkgfileoncmdline = 0;
	my @listlines;
	my @mapfiles;
	my $doconfig = 0;

	if (defined($dh{PRIORITY}) && $dh{PRIORITY} ne '') {
		$priority=$dh{PRIORITY};
	}
	if (defined($dh{FLAVOR})) {
		if ($dh{FLAVOR} eq "config_for_active_maps") {
			$doconfig = 1;
		} elsif ($dh{FLAVOR} eq "config_for_all_maps") {
			$doconfig = 2;
		} else {
			error("Specified flavor $dh{FLAVOR} not supported.\nPlease see man page for supported flavors!\n");
		}
	}
	if ($file) {
		open(FOO, "<$file") || error("$file cannot be opened.");
		@pkgcfg = <FOO>;
		close(FOO);
	}
	if (($package eq $dh{FIRSTPACKAGE} || $dh{PARAMS_ALL}) && @ARGV) {
		foreach my $entry (@ARGV) {
			if ($entry =~ m/^(Map|MixedMap)=(.*)$/) {
				push @cmdlinemaps, "$1 $2";
				if ($doconfig > 0) { push @mapfiles, $2; }
			} elsif ($entry =~ m/^(.*\.cfg)(=([[:digit:]]+))?$/) {
				my $fn=$1;
				my $pr=$priority;
				if (defined($3)) {
					$pr=$3;
				}
				my $bn=basename($fn);
				if ($bn eq "$package.cfg" && $pr == $priority) {
					$pkgfileoncmdline = 1;
				}
				$cmdcfgshash{$fn}=$pr;
			} else {
				error("$entry is neither of the form Map=filename.map, MixedMap=filename.map, or filename.cfg(=priority).");
			}
		}
	}

	@cmdlinecfgs = keys(%cmdcfgshash);
	if (!$file && ($#cmdlinemaps < 0) && ($#cmdlinecfgs < 0)) {
		# we have nothing to do here, skip to the next one!
		next;
	}

	if ($pkgfileoncmdline && ($file || ($#cmdlinemaps >= 0))) {
		error("This call would create multiple copies of $priority$package.cfg.\nPlease read the man page on how this should be fixed!\n");
	}

        if ( ! -d "$tmp/etc/texmf/updmap.d/") {
            doit("install","-d","$tmp/etc/texmf/updmap.d/");
        }
	#
	# the cmd line cfg files
	#
	foreach my $fn (@cmdlinecfgs) {
		my $bn=basename($fn);
		my $pr=$cmdcfgshash{$fn};
		-r "$tmp/etc/texmf/updmap.d/$pr$bn" &&
			error("The config file $tmp/etc/texmf/updmap.d/$pr$bn already exists! Cannot recreate it, please call dh_clean -k!");
		open(CFGFILE, ">$tmp/etc/texmf/updmap.d/$pr$bn") ||
			error("Cannot open $tmp/etc/texmf/updmap.d/$pr$bn for writing!");
		verbose_print("Writing $tmp/etc/texmf/updmap.d/$pr$bn");
		if (!magic_comment_present($fn)) {
			print CFGFILE "# $pr$bn\n";
			print CFGFILE $magicheader;
		}
		open(FOO,"<$fn") || error("Cannot open $fn for reading!");
		while (<FOO>) { 
			my $m;
			print CFGFILE $_; 
			if ($m = extract_map($_, $doconfig)) { push @mapfiles, $m; }
		}
		close(FOO);
		close(CFGFILE);
		$bn =~ s/\.cfg$//;
		push @listlines, "$pr$bn";
	}
	#
	# now debian/package.maps and/or debian/maps
	# merge in the cmd line arguments
	#
	if ($file || ($#cmdlinemaps >= 0)) {
		-r "$tmp/etc/texmf/updmap.d/$priority$package.cfg" &&
			error("The config file $tmp/etc/texmf/updmap.d/$priority$package.cfg already exists! Cannot recreate it, please call dh_clean -k!");
		open(CFGFILE, ">$tmp/etc/texmf/updmap.d/$priority$package.cfg") || 
			error("Cannot open $tmp/etc/texmf/updmap.d/$priority$package.cfg for writing!");
		verbose_print("Writing $tmp/etc/texmf/updmap.d/$priority$package.cfg");
		if (($file && !magic_comment_present($file)) ||
		    (!$file && ($#cmdlinemaps >= 0))) {
			print CFGFILE "# $priority$package.cfg\n";
			print CFGFILE $magicheader;
		}
		foreach (@pkgcfg) {
			my $m;
			print CFGFILE "$_";
			if ($m = extract_map($_, $doconfig)) { push @mapfiles, $m; }
		}
		foreach (@cmdlinemaps) {
			print CFGFILE "$_\n";
		}
		close(CFGFILE);
		push @listlines, "$priority$package";
	}
	
        if ( ! -d "$tmp/var/lib/tex-common/fontmap-cfg/") {
            doit("install","-d","$tmp/var/lib/tex-common/fontmap-cfg/");
        }
	open(LISTFILE, ">>$tmp/var/lib/tex-common/fontmap-cfg/$package.list")||
		error("Cannot open $tmp/var/lib/tex-common/fontmap-cfg/$package.list for writing/appending!");
	verbose_print("Writing $tmp/var/lib/tex-common/fontmap-cfg/$package.list");
	foreach (@listlines) {
		print LISTFILE "$_\n";
	}
	close(LISTFILE);

	if ($#mapfiles >= 0) {
		doit("install","-d","$tmp/usr/share/texmf/dvips/config/");
	}
	foreach my $m (@mapfiles) {
		my $f = $m;
		$f =~ s/\.map$//;
		-r "$tmp/usr/share/texmf/dvips/config/config.$f" &&
			error("The dvips config file $tmp/usr/share/texmf/dvips/config/config.$f already exists!\nYou may have to call dh_clean -k!\n");
		open(CNFFILE, ">$tmp/usr/share/texmf/dvips/config/config.$f") ||
			error("Cannot open $tmp/usr/share/texmf/dvips/config/config.$f for writing!");
		verbose_print("Writing $tmp/usr/share/texmf/dvips/config/config.$f");
		print CNFFILE "p +$m\n";
		close(CNFFILE);
	}
	if (! $dh{NOSCRIPTS}) {
		autoscript($package, "postinst", "postinst-texfonts", "");
		autoscript($package, "postrm",   "postrm-texfonts",   "");
	}

	addsubstvar($package, "misc:Depends", "tex-common", ">= 0.7");
}

=head1 SEE ALSO

L<debhelper(7)>

=head1 AUTHOR

Norbert Preining <preining@logic.at>

=cut
