#!/usr/bin/perl

select STDERR;
$| = 1; # Test for loss of stderr loss
select STDOUT;
$| = 1; # Test (double certainty)

# Shorthands:
$II2USER = $ENV{"II2USER"};
$II2AUTHENTICATED = $ENV{"II2AUTHENTICATED"};
$II2PKGDIR = $ENV{"II2PKGDIR"};
$II2INSTALLDIR = $ENV{"II2INSTALLDIR"};
$II2RESOURCES = $ENV{"II2RESOURCES"};
$II2DOSERVER = $ENV{"II2DOSERVER"};
$II2BUILDSTAMP = $ENV{"II2BUILDSTAMP"};
$II2USERACTION = $ENV{"II2USERACTION"};
$II2LOGLEVEL = $ENV{"II2LOGLEVEL"};
$TEXIPKGSIMPLE = $ENV{"TEXIPKGSIMPLE"};

$simpleinstall = ($TEXIPKGSIMPLE eq 'YES');

if (${II2BUILDSTAMP} < 1167840304) {
    warn "### You need at least i-Installer 2.87 for this package. Bailing out...\n";
    exit 1;
}

$PROGNAME = `"${II2RESOURCES}/basename" "$0"`;
chomp( $PROGNAME);

my $arch = `uname -p`; chomp $arch;

#
print "### ${PROGNAME}: Started...\n";

# Add our installed TeX to the beginning of the PATH so it will always
# be found first. It would be better to add it to the end and check
# with which that we have the right one. Too much work for now.
$ENV{'PATH'} = "${II2INSTALLDIR}/bin/${arch}-apple-darwin-current:$ENV{'PATH'}";

print "### ${PROGNAME}: PATH = \"$ENV{'PATH'}\"\n" if $II2LOGLEVEL > 3;

# Load shared stuff
require "${II2PKGDIR}/texlive.sharedscript.pm";

checkTeXPath();

checkTeXEnvironmentVariables();

migrateifnecessary();

recreatedistributionlinks();

`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 10000`;

setConfigUser();

$stamp = `date "+%Y%m%d%H%M%S"`;
chomp( $stamp);

if (${II2INSTALLDIR} eq "") {
    ipkgwarn( "Your environment is damaged, your Mac OS X installation or your user account is probably damaged. Try running a disk repair program or install from another user's account. Bailing out...\n");
    exit( 1);
}

my $tlversion = 'tl2006';   # Currently only one version available
my $dorunupdmap = 0;	    # Single updmap run
checkPrerequisites();

`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 10000`;

# Set that contains the set selected during the selector phase. This is received
# from i-Installer:
my %set = getSetInfo();

# Global variables that define what we will do during configuration:
my $domacfonts = 0;
my $doselectformats = 0;
my $doselectlanguages = 0;
my $dopapersizeselection = 0;
my $doupdatefontmappings = 0;
my $doownerselection = 0;
my $docliactivation = 0;
my $dohometexactivation = 0;

# Secondary variables that define what needs to be done::
my $docreateformats = 1;
my $dorepairownership = 0;
my $overwritefmtutil;
my $docontextremove = 0;
my $hometexsetting = 0; # We work without any HOMETEX

# Name of saved previous texmf.cnf
my $previoustexmfcnf;

if (-d "${II2INSTALLDIR}/texmf.pkgs/tex/generic/context") {
    my $doremovelocalcontext = 0;
    # More recent versions use \edef instead of \def
    my $localversion = `grep '\\\\e\\?def\\\\contextversion' "${II2INSTALLDIR}/texmf.pkgs/tex/context/base/context.tex"`;
    chomp( $localversion);
    my $basetexversion = `grep '\\\\e\\?def\\\\contextversion' "${II2INSTALLDIR}/texmf.texlive/tex/context/base/context.tex"`;
    chomp( $basetexversion);
    $localversion =~ s/^.*\\e?def\\contextversion\{//;
    $localversion =~ s/\}.*$//;
    $basetexversion =~ s/^.*\\e?def\\contextversion\{//;
    $basetexversion =~ s/\}.*$//;

    if ($simpleinstall) {
	$doremovelocalcontect = 1 if ($localversion le $basetexversion);
    }
    else {
	if ($localversion gt $basetexversion) {
	    my $msg = "I recommend keeping it because it is newer ($localversion) than the version in the System TeX tree ($basetexversion)";
	    $doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Remove (more recent) local ConTeXt install?" -I "I have found a ConTeXt installation in your local tree, possibly installed with the ConTeXt updater i-Package. ${msg}.\n\nDo you want to remove it?." -1 "No" -2 "Yes"`;
	    chomp( $doresult);
	    if (($? >> 8) != 0) {
		$doremovelocalcontect = 1;
	    }
	}
	elsif ($localversion lt $basetexversion) {
	    my $msg = "I recommend removing it because it is out of date ($localversion) with respect to the version in the System TeX tree ($basetexversion)";
	    $doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Remove (older) local ConTeXt install?" -I "I have found a ConTeXt installation in your local tree, possibly installed with the ConTeXt updater i-Package. ${msg}.\n\nDo you want to remove it?." -1 "Yes" -2 "No"`;
	    chomp( $doresult);
	    if (($? >> 8) == 0) {
		$doremovelocalcontect = 1;
	    }
	}
	else {
	    my $msg = "I recommend removing it because it is equal ($localversion) to the version in the System TeX tree ($basetexversion)";
	    $doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Remove local ConTeXt install?" -I "I have found a ConTeXt installation in your local tree, possibly installed with the ConTeXt updater i-Package. ${msg}.\n\nDo you want to remove it?." -1 "Yes" -2 "No"`;
	    chomp( $doresult);
	    if (($? >> 8) == 0) {
		$doremovelocalcontect = 1;
	    }
	}
    }
    if ($doremovelocalcontext) {
	print "### ${PROGNAME}: Removing texmf.pkgs ConTeXt. Please wait...\n";

	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/metapost/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/tex/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/tex/generic/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/tex/latex/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/context/data\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/context/config\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/context/examplap\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/doc/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/scripts/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/fonts/enc/dvips/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/fonts/enc/pftex/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/fonts/map/dvips/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/fonts/map/pftex/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/doc/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/pdftex/config/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/fonts/tfm/hoekwater/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/fonts/type1/hoekwater/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/texmf.pkgs/web2c/natural.tcx\"");
	unlink "${II2INSTALLDIR}/texmf.pkgs/dvips/config/context.map";
	ipkgsystem( "texhash \"${II2INSTALLDIR}/texmf.pkgs\"");
    }
    elsif (($? >> 8) == 2) {
	print "### ${PROGNAME}: Local ConTeXt not removed.\n";
    }
}

`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 10000`;

# Run a texhash on everything (if we just have added something to a texmf
# tree)
# TODO: also do this when there are unconfigured sets
if (${II2USERACTION} eq 'install') {
    print "### ${PROGNAME}: Files may have been added during install, the index needs updating. Please wait....\n";
    ipkgsystem( "texhash");
    if (($? >> 8) != 0) {
	warn "### ${PROGNAME}: Failed to run texhash. Bailing out...\n";
	exit( 1);
    }
    $dorunupdmap = 1;
}

checkTeXInstall();

`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 100000`;

# Configure gwtex font mapping (needs to be done always if gwTeX was installed
# but not yet configured)
if (exists( $set{'tl2006-gwtex'})) {
    if ($set{'tl2006-gwtex'}{'installed'} eq 'YES') {
	if ($set{'tl2006-gwtex'}{'configured'} eq 'NO') {
	    print "### ${PROGNAME}: Enabling map files for gwTeX additions. This is a slow process. Please wait....\n";

	    my $foundrelsymb = 0;
	    my $foundgtamacfonts = 0;

	    my $updmaplistcmd;
	    $updmaplistcmd = '--nohash --listmaps'; # Faster than available maps

	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "Map .+-antt.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Disabling map files with old teTeX names. This is a slow process. Please wait....\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable cork-antt.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable cs-antt.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable exp-antt.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable greek-antt.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable qx-antt.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable t2a-antt.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable t2b-antt.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable t2c-antt.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable t5-antt.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable texnansi-antt.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable wncy-antt.map');
	    }
	    ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map antt.map');
	    ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map iwona.map');

	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "Map cs.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Changing from cs.map to cstext.map and csother.map. This is a slow process. Please wait....\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable cs.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map cstext.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map csother.map');
	    }

	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "Map pl.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Changing from pl.map to pltext.map and plother.map. This is a slow process. Please wait....\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable pl.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map pltext.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map plother.map');
	    }

	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "Map bsr.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Changing from bsr*.map to newer names. This is a slow process. Please wait....\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable bsr-interpolated.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable bsr.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map cmtext-bsr-interpolated.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map cmtext-bsr.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map cmother-bsr-interpolated.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map cmother-bsr.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map latex-bsr.map');
	    }

	    ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable contnav.map');

	    ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable hoekwater.map');
	    ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map mflogo.map');

	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "Map vnr.map" >/dev/null 2>&1') == 0) {
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable vnr.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map vnrtext.map');
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map vnrother.map');
	    }

	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "^Map relsymb.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Found relsymb.map\n";
		$foundrelsymb = 1;
	    }
	    else {
		print "### ${PROGNAME}: Enabling relsymb.map\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map relsymb.map >/dev/null 2>&1 </dev/null');
		$dorunupdmap = 1;
	    }
	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "^Map gtamacfonts.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Found gtamacfonts.map\n";
		$foundgtamacfonts = 1;
		print "### ${PROGNAME}: Disabling gtamacfonts.map (map is loaded by sty files)\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable gtamacfonts.map >/dev/null 2>&1 </dev/null');
		$dorunupdmap = 1;
	    }
	    `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t SetConfiguredSelectorSets -P "tl2006-gwtex"`;
	    print "### ${PROGNAME}: gwTeX maps are configured.\n";
	    print "### ${PROGNAME}: The real update mapping will be performed later.\n" if ($dorunupdmap);
	}
	else {
	    print "### ${PROGNAME}: Map files for gwTeX additions have already been added.\n";
	}
    }
    else {
	print "### ${PROGNAME}:Disabling map files for gwTeX additions. This is a slow process. Please wait....\n";
	ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable relsymb.map >/dev/null 2>&1 </dev/null');
	ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable gtamacfonts.map >/dev/null 2>&1 </dev/null');
    }
}

`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 60000`;

`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 110000`;

# This sets the variables above:
selectConfigureActions();

# And here they are used:
selectFormats() if $doselectformats;
`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 5000`;

selectLanguages() if $doselectlanguages;
`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 5000`;

createFormats() if $docreateformats;
`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 80000`;

selectPaperSize() if $dopapersizeselection;
`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 5000`;

updateFontMappings() if $doupdatefontmappings;
`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 25000`;

if ($domacfonts) {
    macFontUnpacking(); # For GTA Mac Fonts (Mac -> TeX)
    # And for TeX -> Mac:
    my $createverb = (-d "/Library/Fonts/Latin Modern") ? "reinstall" : "install";
    if (not $simpleinstall) {
	my $msg = (${createverb} eq "install" ? "I have not found GUI versions of the Latin Modern fonts of TeX." : "I have found previous GUI versions of the Latin Modern fonts of TeX." ) . " GUI versions can be used in GUI Mac applications like TextEdit or drawing programs like Create.\n\nDo you want to install them?";
	$doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Do you want to ${createverb} GUI Latin Modern fonts?" -I \"${msg}\" -1 "Yes" -2 "No"`;
	chomp( $doresult);
    }
    if (($simpleinstall and (${createverb} eq "install")) or
	(not $simpleinstall and ($? >> 8) == 0)) {
	lmFontInstallation();
    }
}

if ($docliactivation) {
    print "### ${PROGNAME}: Adapting system-wide tcsh settings (path and manpath) if necessary.\n";
    print "### ${PROGNAME}: You need to restart Terminal.app before they are active.\n";
    my $binpath = (-e "/usr/texbin") ? "/usr/texbin" :
	"${II2INSTALLDIR}/bin/${arch}-apple-darwin-current";
    my $manpath = (-e "/Library/TeX/Distributions/.DefaultTeX/Contents/Man") ?
	"/Library/TeX/Distributions/.DefaultTeX/Contents/Man" :
	"${II2INSTALLDIR}/man";
    if (ipkgsystem( "\"${II2PKGDIR}/\"setloginpath foo TeX remove") == 0) {
	print "### ${PROGNAME}: sucessfully removed any CLI path settings.\n";
    }
    if (ipkgsystem( "\"${II2PKGDIR}/\"setloginpath foo setloginpath remove") == 0) {
	print "### ${PROGNAME}: sucessfully removed any CLI path settings.\n";
    }
    if (ipkgsystem( "\"${II2PKGDIR}/\"setloginpath \"$binpath\" TeX") == 0) {
	print "### ${PROGNAME}: sucessfully (re-)added CLI path settings for TeX.\n";
    }
    else {
	warn "### ${PROGNAME}: failed to add CLI path settings for TeX.\n";
    }
    if (ipkgsystem( "\"${II2PKGDIR}/\"setloginpath /usr/local/bin setloginpath") == 0) {
	print "### ${PROGNAME}: sucessfully (re-)added CLI path settings for /usr/local/bin.\n";
    }
    else {
	warn "### ${PROGNAME}: failed to add CLI path settings for /usr/local/bin.\n";
    }
    if (ipkgsystem( "\"${II2PKGDIR}/\"setmanpath foo TeX remove") == 0) {
	print "### ${PROGNAME}: sucessfully removed any man path settings.\n";
    }
    if (ipkgsystem( "\"${II2PKGDIR}/\"setmanpath foo TeXMap remove") == 0) {
	print "### ${PROGNAME}: sucessfully removed any man path map settings.\n";
    }
    if (ipkgsystem( "\"${II2PKGDIR}/\"setmanpath \"MANPATH $manpath\" TeX") == 0) {
	print "### ${PROGNAME}: sucessfully (re-)added man path settings.\n";
    }
    else {
	warn "### ${PROGNAME}: failed to add man path settings.\n";
    }
    if (ipkgsystem( "\"${II2PKGDIR}/\"setmanpath \"MANPATH_MAP $binpath $manpath\" TeXMap") == 0) {
	print "### ${PROGNAME}: sucessfully (re-)added man path settings.\n";
    }
    else {
	warn "### ${PROGNAME}: failed to add man path settings.\n";
    }
}

`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 10000`;

if ($dorunupdmap) {
    do_updmap();
}

`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 50000`;

if ($doownerselection) {
    setOwner();
}
else {
    if ($dorepairownership) {
	print "### ${PROGNAME}: Your configuration may have created a mixed-ownership of files. Fixing...\n";
	my (undef,undef,undef,undef,$uid,$gid,undef) = stat( ${II2INSTALLDIR});
	my $uname = getpwuid( $uid);
	my $group = getgrgid( $gid);
	print "### ${PROGNAME}: Repairing ownership of TeX installation in ${II2INSTALLDIR} to $uname:$group. Please wait...\n";
	ipkgsystem( "/usr/sbin/chown -R \"${uname}:${group}\" ${II2INSTALLDIR}") == 0
	    or die "### ${PROGNAME}: failed to run chown. Bailing out...\n";;
    }
}

`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 5000`;

if ($dohometexactivation) {
    if (not $simpleinstall) {
	my $msg = "Do you want your TeX command line configuration to be backwards compatible with pre-2004 versions? This is recommended because most instructions for the use of TeX command line tools are not only invalid for post-2004 TeX Live, but they also give unexpected and unwanted results like administrator owned files in your home directory.\n\nOnly if you know why you need your personal settings (which this i-Package will ignore if you run it again in the future), choose No.";
	$doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Do you want your CLI setup to be backwards compatible?" -I \"${msg}\" -1 "Yes" -2 "No"`;
	chomp( $doresult);
	if ($doresult eq "Yes") {
	    print "### ${PROGNAME}: Blocking personal configurations support in ${II2INSTALLDIR}/texmf.cnf\n";
	    setHomeTeXUse( 0);
	}
	else {
	    print "### ${PROGNAME}: De-blocking personal configurations support in ${II2INSTALLDIR}/texmf.cnf\n";
	    setHomeTeXUse( 1);
	}
    }
    else {
	if ($previoustexmfcnf ne '') {
	    if (ipkgsystem( "egrep '^GWTEXVAR[[:space:]]*=[[:space:]]*\\\$VARTEXMF' \"${previoustexmfcnf}\" >/dev/null 2>&1") != 0) {
		setHomeTeXUse( 0);
	    }
	    else {
		setHomeTeXUse( 1);
	    }
	}
    }
}

`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 5000`;

warn "### ${PROGNAME}: Finished.\n";
print "### ${PROGNAME}: Finished.\n";

exit( 0);

sub ismap
{
    my $mapname = shift;

    return( ipkgsystem( "${updmapcmd} " . "--listmaps 2>/dev/null </dev/null | grep \"$mapname\" >/dev/null") == 0);
}

sub addmap
{
    my $maptype = shift;
    my $mapname = shift;
    my $active = shift;

    if (!&ismap( $mapname)) {
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable $maptype $mapname >/dev/null 2>&1 </dev/null");
	if ($active ne "yes") {
	    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --disable $mapname >/dev/null 2>&1 </dev/null");
	}
    }
}

sub selectConfigureActions
{
    if ($simpleinstall) {
	$doselectformats = 1; # This one catches simpleinstall
	$doselectlanguages = 1; # This one catches simpleinstall
	$docreateformats = 1;
	$domacfonts = 1;
	$dopapersizeselection = 1;
	$doupdatefontmappings = 0;
	$doownerselection = 0;
	$docliactivation = 1;
	$dorepairownership = 1;
	$dohometexactivation = 0;
	return;
    }
    my $choiceString;

    $choiceString = "-Formats Selection|-Languages Selection|";
    if ((exists( $set{'tl2006-bin-${arch}'}) and not
	 ($set{'tl2006-bin-${arch}'}{'configured'} eq 'YES')) or
	(exists( $set{'tl2006-texmfe'}) and not
	 ($set{'tl2006-texmfe'}{'configured'} eq 'YES'))) {
	warn "### ${PROGNAME}: Essential TeX programs or foundation have not been configured yet. A create formats is recommended\n";
	$docreateformats = 1;
	$dorepairownership = 1;
	$choiceString .= "+Formats Creation|+Paper Size Selection|+Mac Fonts|-Update Font Mappings|-TeX Owner Selection|+CLI Activation|-Personal Config Activation"
    }
    else {
	$choiceString .= "-Formats Creation|-Paper Size Selection|-Mac Fonts|-Update Font Mappings|-TeX Owner Selection|-CLI Activation|-Personal Config Activation"
    }
    # It would be nice if CLI activation was detected and then not selected by default

    $doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Select -C "$choiceString"  -T "Configure what?" -I "Select which user selectable configuration actions you want to perform.\n\nSome configuration actions are executed independent of your selection unless you choose Cancel now" -1 "Select" -2 "Everything" -3 "Cancel"`;
    chomp( $doresult);
    if (($? >> 8) == 0) {
	$doselectformats = $doresult =~ /\+Formats Selection/;
	$doselectlanguages = $doresult =~ /\+Languages Selection/;
	$docreateformats = $doresult =~ /\+Formats Creation/;
	$domacfonts = $doresult =~ /\+Mac Fonts/;
	$dopapersizeselection = $doresult =~ /\+Paper Size Selection/;
	$doupdatefontmappings = $doresult =~ /\+Update Font Mappings/;
	$doownerselection = $doresult =~ /\+TeX Owner Selection/;
	$docliactivation = $doresult =~ /\+CLI Activation/;
	$dohometexactivation = $doresult =~ /\+Personal Config Activation/;
	if (($doselectformats or $doselectlanguages) and not $docreateformats) {
	    $doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Initialize TeX?" -I "You chose not to initialize TeX, but you do want to change formats or languages settings. Without initialization after setting changes, any format and language settings will not be activated and TeX will probably not function properly.\n\nChoose YES when in doubt." -1 "Yes" -3 "No"`;
	    chomp( $doresult);
	    if (($? >> 8) == 0) {
		$docreateformats = 1;
	    }
	}
	my $thereisafmt = -f "${II2INSTALLDIR}/texmf.local/web2c/pdflatex.fmt";
	if (not $docreateformats and ! $thereisafmt) {
	    warn "### ${PROGNAME}: It seems your TeX is completely uninitialized.\n";
	    $doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Initialize TeX?" -I "You chose not to initialize TeX, but it seems you TeX has never been initalized. Without initialization, TeX will NOT function properly. Initialize?\n\nChoose YES when in doubt." -1 "Yes" -3 "No"`;
	    chomp( $doresult);
	    if (($? >> 8) == 0) {
		$docreateformats = 1;
	    }
	}
    }
    elsif (($? >> 8) == 1) {
	print "### ${PROGNAME}: Not configuring TeX. Bailing out gracefully...\n";
	exit( 0);
    }
    elsif (($? >> 8) == 2) {
	# Everything
	$doselectformats = 1;
	$doselectlanguages = 1;
	$docreateformats = 1;
	$domacfonts = 1;
	$dopapersizeselection = 1;
	$doupdatefontmappings = 1;
	$doownerselection = 1;
	$docliactivation = 1;
	$dohometexactivation = 1;
    }
}

sub checkPrerequisites
{
    if (not -x "/usr/bin/grep") {
	print "### ${PROGNAME}: TeX needs commands from the BSD subsystem to run. The BSD subsystem seems to be missing on this system. Bailing out...\n";
	exit( 1);
    }

    if (${II2INSTALLDIR} eq "") {
	warn "### ${PROGNAME}: ${II2INSTALLDIR} is empty. No TeX found.\n";
	warn "### ${PROGNAME}: I cannot configure a nonexistent TeX. Bailing out gracefully...\n";
	exit( 0);
    }

    if (not -e "${II2INSTALLDIR}/texmf/web2c/pdftex.pool" or not -e "${II2INSTALLDIR}/bin/${arch}-apple-darwin-current/pdfetex") {
	warn "### ${PROGNAME}: No (complete) TeX Programs found. Configuration cannot proceed.\n";
	warn "### ${PROGNAME}: Configuration will be possible when both TeX Programs and TeX Foundation are available.\n";
	warn "### ${PROGNAME}: Note, this is not an error. Just install TeX Programs now.\n";
	warn "### ${PROGNAME}: Bailing out gracefully...\n";
	`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "TeX Programs Unavailable" -I "TeX cannot be configured because the TeX Programs have not been installed yet. Only when both foundation and programs have been installed (in either order) will the configuration script proceeed. Just install TeX Programs now." -1 "OK"`;
	exit( 0);
    }

    if ( ! -e "${II2INSTALLDIR}/texmf.local" ) {
	print "### ${PROGNAME}: ${II2INSTALLDIR}/texmf.local does not exist. Creating.\n";
	mkdir( "${II2INSTALLDIR}/texmf.local");
    }

    if ( ! -e "${II2INSTALLDIR}/texmf.pkgs" ) {
	print "### ${PROGNAME}: ${II2INSTALLDIR}/texmf.pkgs does not exist. Creating.\n";
	mkdir( "${II2INSTALLDIR}/texmf.pkgs");
    }

    if ( ! -e "${II2INSTALLDIR}/texmf.cnf" ) {
	print "### ${PROGNAME}: ${II2INSTALLDIR}/texmf.cnf does not exist. Creating default.\n";
	ipkgsystem( "cp \"${II2PKGDIR}/texmf.cnf.${tlversion}\" \"${II2INSTALLDIR}/texmf.cnf\"") == 0
	    or die "### ${PROGNAME}: failed to install a new texmf.cnf. Bailing out...\n";
    }
    elsif ( ipkgsystem( "/usr/bin/cmp -s \"${II2INSTALLDIR}/texmf.cnf\" \"${II2PKGDIR}/texmf.cnf.${tlversion}\"") != 0) {
	$previoustexmfcnf = "texmf.cnf.$stamp";
	print "### ${PROGNAME}: ${II2INSTALLDIR}/texmf.cnf differs from current standard. Either you have modified it or I have updated the standard. Creating default and saving your original version as \"${II2INSTALLDIR}/${previoustexmfcnf}\". Diff was:\n";
	ipkgsystem( "/usr/bin/diff -C 2 \"${II2INSTALLDIR}/texmf.cnf\" \"${II2PKGDIR}/texmf.cnf.${tlversion}\"");
	ipkgsystem( "mv \"${II2INSTALLDIR}/texmf.cnf\" \"${II2INSTALLDIR}/${previoustexmfcnf}\"" );
	ipkgsystem( "cp \"${II2PKGDIR}/texmf.cnf.${tlversion}\" \"${II2INSTALLDIR}/texmf.cnf\"") == 0
	    or die "### ${PROGNAME}: failed to install a new texmf.cnf. Bailing out...\n";
    }

    if ( ! -w "${II2INSTALLDIR}/texmf.local" or ! -d "${II2INSTALLDIR}/texmf.local" ) {
	warn "### ${PROGNAME}: ${II2INSTALLDIR}/texmf.local is not writable or not found.\n";
	warn "### ${PROGNAME}: I cannot configure a nonwritable TeX. Bailing out...\n";
	exit( 1);
    }

    if ( -d "${II2INSTALLDIR}/texmf.texlive/dvipdfm/config" and  -f "${II2INSTALLDIR}/texmf.local/dvipdfm/config" ) {
	warn "### ${PROGNAME}: ${II2INSTALLDIR}/texmf.local/dvipdfm/config is not a directory while the one from TeX is. Adapting...\n";
	ipkgsystem( "mv \"${II2INSTALLDIR}/texmf.local/dvipdfm/config\" \"${II2INSTALLDIR}/texmf.local/dvipdfm/config.temp\"") == 0
	    or die "### ${PROGNAME}: failed to temporarily move dvipdfm/config. Bailing out...\n";
	ipkgsystem( "mkdir \"${II2INSTALLDIR}/texmf.local/dvipdfm/config\"") == 0
	    or die "### ${PROGNAME}: failed to create dvipdfm/config directory. Bailing out...\n";
	ipkgsystem( "mv \"${II2INSTALLDIR}/texmf.local/dvipdfm/config.temp\" \"${II2INSTALLDIR}/texmf.local/dvipdfm/config/config\"") == 0
	    or die "### ${PROGNAME}: failed to move config file into new dvipdfm config dir. Bailing out...\n";
    }

    if ( ! -e "${II2INSTALLDIR}/texmf/web2c/updmap.cfg" ) {
	print "### ${PROGNAME}: ${II2INSTALLDIR}/texmf/web2c/updmap.cfg does not exist. Creating default.\n";
	ipkgsystem( "cp \"${II2PKGDIR}/updmap.cfg.${tlversion}\" \"${II2INSTALLDIR}/texmf/web2c/updmap.cfg\"") == 0
	    or die "### ${PROGNAME}: failed to install new updmap.cfg. Bailing out...\n";
	ipkgsystem( "texhash \"${II2INSTALLDIR}/texmf\"");
    }

    if ( ! -e "${II2INSTALLDIR}/texmf/web2c/fmtutil.cnf" ) {
	print "### ${PROGNAME}: ${II2INSTALLDIR}/texmf/web2c/fmtutil.cnf does not exist. Creating default.\n";
	ipkgsystem( "cp \"${II2PKGDIR}/fmtutil.cnf.${tlversion}\" \"${II2INSTALLDIR}/texmf/web2c/fmtutil.cnf\"") == 0
	    or die "### ${PROGNAME}: failed to install new fmtutil.cnf. Bailing out...\n";
	ipkgsystem( "texhash \"${II2INSTALLDIR}/texmf\"");
    }

    if ( ! -e "${II2INSTALLDIR}/texmf/web2c/mktex.cnf" ) {
	print "### ${PROGNAME}: ${II2INSTALLDIR}/texmf/web2c/mktex.cnf does not exist. Creating default.\n";
	ipkgsystem( "cp \"${II2PKGDIR}/mktex.cnf.${tlversion}\" \"${II2INSTALLDIR}/texmf/web2c/mktex.cnf\"") == 0
	    or die "### ${PROGNAME}: failed to install new mktex.cnf. Bailing out...\n";
	ipkgsystem( "texhash \"${II2INSTALLDIR}/texmf\"");
    }

    # Overwrite texmf/web2c/texmf.cnf with our own as it has a trie-size
    # that is large enough for all languages to be present simultaneously and
    # thus does not produce an endless loop during configuration.
    # This is a fix until the binaries are made with a proper trie-size
    # in web2c/texmf.cnf
    ipkgsystem( "cp \"${II2PKGDIR}/texmf.cnf.web2c.${tlversion}\" \"${II2INSTALLDIR}/texmf/web2c/texmf.cnf\"") == 0
	or die "### ${PROGNAME}: failed to install our own web2c/texmf.cnf. Bailing out...\n";

    checkFmtutilCfg();

    checkPersonalConfigs();
}

sub checkFmtutilCfg
{
    my $redirect = "1>&2";
    $redirect = '>/dev/null 2>&1' if ($II2LOGLEVEL < 6);

    $fmtutilloc = `${kpsewhichcmd} --format='web2c files' fmtutil.cnf`;
    chomp( $fmtutilloc);
    if ($fmtutilloc eq '') {
	die "### ${PROGNAME}: fmtutil.cnf is missing. Bailing out...\n";
    }
    ipkgsystem( "egrep '^[[:alnum:]]+[[:space:]]+mfw?[[:space:]]' \"$fmtutilloc\" ${redirect}");
    if (($? >> 8) == 0) {
	$overwritefmtutil = 1;
	$dorepairownership = 1;
	warn "### ${PROGNAME}: fmtutil.cnf is not X11-safe. Repair imminent...\n";
    }
    ipkgsystem( "egrep '^latex[[:space:]]+pdftex[[:space:]]' \"$fmtutilloc\" ${redirect}");
    if (($? >> 8) != 0) {
	$overwritefmtutil = 1;
	$dorepairownership = 1;
	warn "### ${PROGNAME}: fmtutil.cnf contains non-PDFTeX LaTeX. Repair imminent...\n" if $tlversion eq "tl2003";
    }
    ipkgsystem( "egrep '^pdfetex[[:space:]]+pdftex[[:space:]]' \"$fmtutilloc\" ${redirect}");
    if (($? >> 8) != 0) {
	$overwritefmtutil = 1;
	$dorepairownership = 1;
	warn "### ${PROGNAME}: fmtutil.cnf contains non-PDFTeX PDFE-TeX. Repair imminent...\n";
    }

    ipkgsystem( "egrep '[[:space:]]+-translate-file' \"$fmtutilloc\" >/dev/null ${redirect}");
    if (($? >> 8) != 0) {
	$overwritefmtutil = 1;
	$dorepairownership = 1;
	warn "### ${PROGNAME}: fmtutil.cnf does not contain TL2004 structure. Repair imminent...\n";
    }

    if ($overwritefmtutil) {
	if (not $simpleinstall) {
	    $doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Save fmtutil.cnf copy?" -I "An outdated fmtutil.cnf has been found. That may even happen on a fresh install because the one in the archive might be older than the one in the package. A new version will be installed. Do you want a copy transferred to your desktop so you can merge your changes with the new format? Or do you want to drop the old version? Only keep the old version if you are a unix and TeX expert and you have changed your settings extensively." -1 "Copy" -2 "Drop"`;
	    chomp( $doresult);
	    if (($? >> 8) == 0) {
		$stamp=`date "+%Y%m%d%H%M"`; chomp( $stamp);
		print "### ${PROGNAME}: Saving copy of fmtutil.cnf on your desktop.\n";
		ipkgsystem( "cp \"$fmtutilloc\" \"\$\{HOME\}/Desktop/fmtutil.cnf.$stamp\"") == 0
		    or die "### ${PROGNAME}: failed to save copy of fmtutil.cnf. Bailing out...\n";
		ipkgsystem( "/usr/sbin/chown \"\$\{USER\}\" \"\$\{HOME\}/Desktop/fmtutil.cnf.$stamp\"") == 0
		    or warn "### ${PROGNAME}: failed to change ownership on fmtutil.cnf.$stamp.\n";
	    }
	}
	print "### ${PROGNAME}: Installing a current, X11-safe $tlversion fmtutil.cnf.\n";
	ipkgsystem( "cp \"${II2PKGDIR}/fmtutil.cnf.${tlversion}\" \"$fmtutilloc\"") == 0
	    or die "### ${PROGNAME}: failed to install new fmtutil.cnf. Bailing out...\n";
    }
}

sub selectFormats
{
    if ($simpleinstall) {
	ipkgsystem( "${fmtutilcmd} --enablefmt tex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable tex\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt etex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable etex\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt pdftex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable pdftex\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt pdfetex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable pdfetex\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt latex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable latex\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt pdflatex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable pdflatex\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt mf </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable metafont\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt mpost </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable metapost\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt metafun </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable metafun\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt omega </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable omega\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt lambda </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable lambda\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt amstex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable amstex\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt xetex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable xetex\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt xeplain </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable xeplain\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt xelatex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable xelatex\n";

	foreach my $ctxfmt (('cont-en', 'cont-nl', 'cont-cz', 'cont-de', 'cont-uk', 'cont-it', 'cont-ro', 'cont-fr', 'mptopdf', 'metafun')) {
	    ipkgsystem( "${fmtutilcmd} --disablefmt $ctxfmt </dev/null") == 0
		or warn "### ${PROGNAME}: failed to disable ConTeXt ($ctxfmt) in fmtutil\n";
	}
	return;
    }
    REDOFMTS: $try = 1;
    %activeformats = undef;
    %inactiveformats = undef;
    do {
	$langformats = '';
	$displayString = '';
	if (open( FDAT, "${fmtutilcmd} --listcfg|")) {
	    @formatlist = <FDAT>;
	    close FDAT;
	    if ($#formatlist > 0) {
		foreach $fmtitem (@formatlist) {
		    if ($fmtitem =~ /\s*#!\s*(\S+)\s+\S+\s+(\S+)/) {
			next if $1 =~ /cont-[a-z][a-z]/; # Ignore ConTeXt
			$displayString .= "-$1|";
			$patternfile = $2;
			if ($patternfile eq 'language.dat') {
			    $langformats .= "$1, ";
			}
			$inactiveformats{$1} = 1;
			next;
		    }
		    if ($fmtitem =~ /\s*(\S+)\s+\S+\s+(\S+)/) {
			if ($1 =~ /cont-[a-z][a-z]/) {
			    ipkgsystem( "${fmtutilcmd} --disablefmt $1 </dev/null") == 0
				or warn "### ${PROGNAME}: failed to disable ConTeXt ($1) in fmtutil\n";
			    next;
			}
			$displayString .= "+$1|";
			$patternfile = $2;
			if ($patternfile eq 'language.dat') {
			    $langformats .= "$1, ";
			}
			$activeformats{$1} = 1;
		    }
		}
		chop( $displayString);
	    }
	    else {
		print "### ${PROGNAME}: This TeX does not hav a new format fmtutil.cnf. Installing one.\n";
		$fmtutilloc = `${kpsewhichcmd} --format='web2c files' fmtutil.cnf`;
		chomp( $fmtutilloc);
		ipkgsystem( "cp \"${II2PKGDIR}/fmtutil.cnf.${tlversion}\" \"$fmtutilloc\"") == 0
		    or die "### ${PROGNAME}: failed to install new fmtutil.cnf. Bailing out...\n";
	    }
	}
	else {
	    warn "### ${PROGNAME}: Failed to get list of formats. Bailing out...\n";
	    exit( 1);
	}
    }
    while ($try-- > 0);
    chop( $langformats);
    chop( $langformats);

    $doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Select -T "Select Formats" -C "$displayString" -I "Please activate all required formats from this list. (Disabling LaTeX and pdfLaTeX will be ignored). Choosing Reset will first install a default set and the offer you another go at modification. Choose No Change after that if you want to keep the default set." -1 "Set" -2 "Reset" -3 "No Change"`;
    chomp( $doresult);

    if (($? >> 8) == 0) {
	$dorepairownership = 1;
	print "### ${PROGNAME}: Changing existing config file for formats.\n";
	@newformatlist = split( /\|/, $doresult);
	grep( do {
	    my ($active, $format) = /^([-+])(\S+)/;
	    if ((exists $activeformats{$format}) and ($active eq '-')) {
		print "### ${PROGNAME}: Disabling $format\n";
		ipkgsystem( "${fmtutilcmd} --disablefmt $format </dev/null") == 0
		    or warn "### ${PROGNAME}: failed to disable $format\n";
		delete $activeformats{$format};
		$inactiveformats{$format} = 1;
	    }
	    elsif ((exists $inactiveformats{$format}) and ($active eq '+')) {
		print "### ${PROGNAME}: Enabling $format\n";
		ipkgsystem( "${fmtutilcmd} --enablefmt $format </dev/null") == 0
		    or warn "### ${PROGNAME}: failed to enable $format\n";
		delete $inactiveformats{$format};
		$activeformats{$format} = 1;
	    }
	}, @newformatlist);

	# Always activate these:
	for my $fmtname (('latex', 'pdflatex', 'xelatex', 'xetex', 'xeplain')) {
	    if (not exists $activeformats{$fmtname}) {
		warn "### ${PROGNAME}: $fmtname cannot be disabled by this script. Enabling...\n";
		ipkgsystem( "${fmtutilcmd} --enablefmt $fmtname </dev/null") == 0
		    or warn "### ${PROGNAME}: failed to enable $fmtname\n";
	    }
	}
    }
    elsif (($? >> 8) == 2) {
	# Default
	$dorepairownership = 1;
	print "### ${PROGNAME}: Installing default config file for formats.\n";
	$fmtutilloc = `${kpsewhichcmd} --format='web2c files' fmtutil.cnf`;
	chomp( $fmtutilloc);
	ipkgsystem( "cp \"${II2PKGDIR}/fmtutil.cnf.${tlversion}\" \"$fmtutilloc\"") == 0
	    or die "### ${PROGNAME}: failed to install new fmtutil.cnf. Bailing out...\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt latex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable latex\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt pdflatex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable pdflatex\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt xelatex </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable xelatex\n";
	# Always deactive these:
	foreach my $ctxfmt (('cont-en', 'cont-nl', 'cont-cz', 'cont-de', 'cont-uk', 'cont-it', 'cont-ro', 'cont-fr', 'mptopdf', 'metafun')) {
	    ipkgsystem( "${fmtutilcmd} --disablefmt $ctxfmt </dev/null") == 0
		or warn "### ${PROGNAME}: failed to disable ConTeXt ($ctxfmt) in fmtutil\n";
	}
	goto REDOFMTS;
    }
    else {
	print "### ${PROGNAME}: Current config file for formats will not be changed.\n";
    }
}

sub selectLanguages
{
    my $texmfvardir = undef;
    my $sudostring = "";
    if (defined $configforuser and $configforuser ne 'root') {
	$sudostring = "";
	$texmfvardir = `${sudostring} kpsewhich -var-value=TEXMFVAR`;
    }
    else {
	$sudostring = "sudo -H -u root";
	$texmfvardir = `${sudostring} kpsewhich -var-value=TEXMFSYSVAR`;
    }
    if (not defined $texmfvardir) {
	$texmfvardir = `kpsewhich -var-value=TEXMFLOCAL`;
    }
    chomp( $texmfvardir);
    $languagedat_out_dir = "$texmfvardir/tex/generic/config";
    $languagedat_out = "$languagedat_out_dir/language.dat";
    ipkgsystem( "${sudostring} /bin/mkdir -p \"$languagedat_out_dir\"");
    $languagedat_in = `${sudostring} kpsewhich -format=.tex language.dat`;
    chomp( $languagedat_in);
    warn "### ${PROGNAME} Source: $languagedat_in, Destination: $languagedat_out\n";
    if ($simpleinstall) {
	# A reasonable default set:
	$defaultlanguages{'english'} = 1;
	$defaultlanguages{'german'} = 1;
	$defaultlanguages{'ngerman'} = 1;
	$defaultlanguages{'french'} = 1;
	$defaultlanguages{'italian'} = 1;
	$defaultlanguages{'spanish'} = 1;
	$defaultlanguages{'dutch'} = 1;
	if (open( LDAT, "<${languagedat_in}")) {
	    @languagedat = <LDAT>;
	    close LDAT;
	    my $lastlang = '';
	    if (ipkgsystem( "${sudostring} /usr/bin/touch \"$languagedat_out\"") == 0 and
		open( LDAT, ">${languagedat_out}")) {
		foreach $langitem (@languagedat) {
		    #warn "READING: $langitem";
		    if ($langitem =~ /^\s*(%[^!].*)?$/) { # Empty or commentline
		    }
		    elsif ($langitem =~ /^\s*(%!)?\s*=(\S+)/) {	# Alias
			#warn "Alias: $2 ($1) ($3)\n";
			$outcommented = ( $1 eq '%!' );
			if ($lastlang ne '') {
			    if ($outcommented) {
				# Make active
				#warn "Alias: activating $langitem";
				$langitem =~ s/^\s*%!\s*//;
			    }
			}
			else {
			    if (not $outcommented) {
				# Make alias inactive because source is also
				#warn "Alias: de-activating $langitem";
				$langitem = "%! " . $langitem;
			    }
			}
		    }
		    elsif ($langitem =~ /^\s*(%!)?\s*(\S+)\s+(\S+)/) { # Entry
			#warn "Entry: $2 ($1) ($3)\n";
			$outcommented = ( $1 eq '%!' );
			my $hyphenfilefound = `${kpsewhichcmd} -format=.tex $3`;
			chomp( $hyphenfilefound);
			if ($hyphenfilefound eq '') {
			    warn "### Hyphenfile $3 is not available, initialization will fail if it remains active. Deselecting $2...\n";
			}
			if ($hyphenfilefound ne '' and
			    (not $outcommented or exists $defaultlanguages{$2})) {
			    $lastlang = $2;
			    #warn "Entry: inactive $langitem\n";
			    if ($outcommented) {
				# Make active
				#warn "Entry: activating $langitem\n";
				$langitem =~ s/^\s*%!\s*//;
			    }
			}
			else {
			    $lastlang = '';
			    #warn "Entry: active $langitem\n";
			    if (not $outcommented) {
				# Make inactive
				#warn "Entry: de-activating $langitem\n";
				$langitem = "%! " . $langitem;
			    }
			}
		    }
		    print LDAT $langitem;
		}
		close LDAT;
	    }
	    else {
		warn "### ${PROGNAME}: Cannot write language.dat. Bailing out...\n";
		exit( 1);
	    }
	}
	else {
	    warn "### ${PROGNAME}: Cannot read language.dat. Bailing out...\n";
	    exit( 1);
	}
	return;
    }
    # Set languages for latex and friends
    REDOLANGUAGES: 
    %langalias = undef;
    %hyphen = undef;
    %activelanguages = undef;
    %inactivelanguages = undef;
    %firstlang = undef;
    %firsthyph = undef;
    $displayString = '';
    if (open( LDAT, "<${languagedat_in}")) {
	@languagedat = <LDAT>;
	close LDAT;
	foreach $langitem (@languagedat) {
	    # warn "READING: $langitem";
	    next if ($langitem =~ /^\s*(%[^!].*)?$/); # Empty or commentline
	    if ($langitem =~ /^\s*(%!)?\s*=(\S+)/) {	# Alias
		# warn "Alias: $langitem";
		$alias = $2;
		$langalias{$alias} = $lang;	# Alias for last language
		next;
	    }
	    if ($langitem =~ /^\s*(%!)?\s*(\S+)\s+(\S+)/) { # Entry
		# warn "Entry: $langitem";
		$outcommented = ( $1 eq '%!' );
		$lang = $2;
		$hyph = $3;
		$hyphen{$lang} = $hyph;
		if ($outcommented) {
		    $displayString .= "-$lang ($hyph)|";
		    $inactivelanguages{"$lang ($hyph)"} = 1;
		}
		else {
		    $hyphenfilefound = `${kpsewhichcmd} -format=.tex $hyph`;
		    chomp( $hyphenfilefound);
		    if ($hyphenfilefound eq '') {
			warn "### Hyphenfile $hyph is not available, initialization will fail! Deselect $lang\n";
			$displayString .= "-$lang ($hyph)|";
			$inactivelanguages{"$lang ($hyph)"} = 1;
		    }
		    else {
			$displayString .= "+$lang ($hyph)|";
			$activelanguages{"$lang ($hyph)"} = 1;
		    }
		}
		if (not exists $firsthyph{$lang}) {
		    # Always keep this available:
		    $firstlang{$lang} = $hyph;
		    $firsthyph{$hyph} = $lang;
		}
		next;
	    }
	}
	chop( $displayString);
    }
    else {
	warn "### ${PROGNAME}: Cannot read language.dat. Bailing out...\n";
	exit( 1);
    }

    $doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Select -T "Select Languages for LaTeX" -C "$displayString" -I "Please activate all required languages from this list (this setting influences: $langformats). Choosing Reset will install default set and return to this panel to offer you a chance of modification. Choose No Change if you want to keep whatever is presented when this sheet starts." -1 "Set" -2 "Reset" -3 "No Change"`;
    chomp( $doresult);

    if (($? >> 8) == 0) {
	$dorepairownership = 1;
	print "### ${PROGNAME}: Adapting current config file for languages...\n";
	@newlanguagedat = split( /\|/, $doresult);
	grep( do {
	    my ($active,$lang, $hyph) = /^([-+])(\S+)\s*\((\S+)\)/;
	    if ((exists $inactivelanguages{"$lang ($hyph)"}) and ($active eq '+')) {
		$hyphenfilefound = `${kpsewhichcmd} -format=.tex $hyph`;
		chomp( $hyphenfilefound);
		if ($hyphenfilefound eq '') {
		    warn "### Hyphenfile $hyph is not available, I will not enable it.\n";
		    delete $activelanguages{"$lang ($hyph)"};
		    $inactivelanguages{"$lang ($hyph)"} = 1;
		}
		else {
		    print "### ${PROGNAME}: Enabling $lang ($hyph)\n";
		    delete $inactivelanguages{"$lang ($hyph)"};
		    $activelanguages{"$lang ($hyph)"} = 1;
		}
	    }
	    elsif ((exists $activelanguages{"$lang ($hyph)"}) and ($active eq '-')) {
		print "### ${PROGNAME}: Disabling $lang ($hyph)\n";
		delete $activelanguages{"$lang ($hyph)"};
		$inactivelanguages{"$lang ($hyph)"} = 1;
	    }
	}, @newlanguagedat);

	@resultdat = ();
	%languagesfound = undef;
	foreach $langitem (@languagedat) {
	    # warn "HANDLING: $langitem";
	    if ($langitem =~ /^\s*(%[^!].*)?$/) {	# Empty or commentline
		# warn "Empty/comment: $langitem";
		push( @resultdat, $langitem);
		next;
	    }
	    if ($langitem =~ /^\s*(%!)?\s*=(\S+)(\s+%.*)?/) {	# Alias
		# warn "Alias $alias: $langitem";
		$outcommented = $1;
		$alias = $2;
		$comment = $3;
		if ($lastisactive or $alias eq "english") {
		    push( @resultdat, "=$alias$comment\n");
		}
		else {
		    push( @resultdat, "%! =$alias$comment\n");
		}
		next;
	    }
	    if ($langitem =~ /^\s*(%!\s*)?(\S+)\s+(\S+)(\s+%.*)?/) {	# Entry
		# warn "Entry: $langitem";
		$outcommented = $1;
		$lang = $2;
		$hyph = $3;
		$comment = $4;
		if (not exists $languagesfound{$lang}) {
		    if (exists $activelanguages{"$lang ($hyph)"} or $lang eq "nohyphenation") {
			$lastisactive = 1;
			push( @resultdat, "$lang\t$hyph$comment\n");
			$languagesfound{$lang} = 1;
		    }
		    else {
			$lastisactive = 0;
			push( @resultdat, "%! $lang\t$hyph$comment\n");
		    }
		}
		else {
		    warn "### ${PROGNAME}: Language $lang already activated. Will not enable two hyphenation patterns for one language. Make sure only one hyphenation pattern is selected for each language\n";
		    $lastisactive = 0;
		    push( @resultdat, "%! $lang\t$hyph$comment\n");
		}
		next;
	    }
	}

	if (ipkgsystem( "${sudostring} /usr/bin/touch \"$languagedat_out\"") == 0 and
	    open( LDAT, ">${languagedat_out}")) {
	    print LDAT @resultdat;
	    close LDAT;
	    warn "### ${PROGNAME}: Force creation of formats because language.dat may have changed and formats may be affected." if $docreateformats == 0;
	    $docreateformats=1;
	}
	else {
	    warn "### ${PROGNAME}: Cannot write language.dat. Bailing out...\n";
	    exit( 1);
	}
    }
    elsif (($? >> 8) == 2) {
	# Default
	$dorepairownership = 1;
	print "### ${PROGNAME}: Installing default config file for languages...\n";
	ipkgsystem( "cp \"${II2PKGDIR}/language.dat.${tlversion}\" \"$languagedat_out\"") == 0
	    or die "### ${PROGNAME}: failed to install new language.dat. Bailing out...\n";
	goto REDOLANGUAGES;
    }
    else {
	print "### ${PROGNAME}: Current config file for languages will not be changed.\n";
    }
}

sub selectPaperSize
{
    if ($simpleinstall) {
	my $syspapersizeline = `defaults find DefaultPaperID`;
	chomp( $syspapersizeline);
	if ($syspapersizeline =~ /\{\s*DefaultPaperID\s*=\s*\"([^"]+)\"\s*;\s*\}/) {
	    my $syspapersize = $1;
	    $syspapersize =~ s/^iso-//;
	    $syspapersize =~ s/^na-//;
	    print "### ${PROGNAME}: Detected paper size $syspapersize for $II2USER.\n";
	    $syspapersize =~ tr [A-Z] [a-z];
	    $dorepairownership = 1;
	    print "### ${PROGNAME}: Setting paper size $syspapersize for dvips ...\n";
	    ipkgsystem( "${texconfigcmd} dvips paper $syspapersize </dev/null") == 0
		or warn "### ${PROGNAME}: failed to set papersize $syspapersize for dvips\n";
	    print "### ${PROGNAME}: Setting paper size $syspapersize for pdfTeX ...\n";
	    ipkgsystem( "${texconfigcmd} pdftex paper $syspapersize </dev/null") == 0
		or warn "### ${PROGNAME}: failed to set papersize $syspapersize for pdftex\n";
	    return;
	}
    }
    REDOPAPERSIZE:
    if ($simpleinstall) {
	@displayArray = ( "select paper size", "a4", "letter");
    }
    else {
	@displayArray = ( "select paper size", "a4", "letter", "legal", "ledger", "tabloid", "a3", "unknown");
    }

    $displayString = '';

    foreach my $choice (@displayArray) {
	$displayString .= "$choice|";
    }
    chop( $displayString);

    $doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Choice -T "Select Paper Size" -C "$displayString" -I "Please select a default paper size for pdfTeX and dvips from the options below. If you do not want to set it, choose No Change, if you select Set and the value is still \\\"select paper size\\\" you will get this panel again." -1 "Set" -2 "Default (A4)" -3 "No Change"`;
    chomp( $doresult);

    if (($? >> 8) == 0) {
	$dorepairownership = 1;
	goto REDOPAPERSIZE if ($doresult eq "select paper size");
	print "### ${PROGNAME}: Setting paper size $doresult for dvips ...\n";
	ipkgsystem( "${texconfigcmd} dvips paper $doresult </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to set papersize $doresult for dvips\n";
	print "### ${PROGNAME}: Setting paper size $doresult for pdfTeX ...\n";
	ipkgsystem( "${texconfigcmd} pdftex paper $doresult </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to set papersize $doresult for pdftex\n";
    }
    elsif (($? >> 8) == 2) {
	$dorepairownership = 1;
	print "### ${PROGNAME}: Setting paper size a4 for dvips ...\n";
	ipkgsystem( "${texconfigcmd} dvips paper a4 </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to set papersize a4 for dvips\n";
	print "### ${PROGNAME}: Setting paper size a4 for pdfTeX ...\n";
	ipkgsystem( "${texconfigcmd} pdftex paper a4 </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to set papersize a4 for pdftex\n";
    }
    else {
	print "### ${PROGNAME}: Keeping current paper size for dvips and pdfTeX.\n";
    }
}

sub createFormats {
    $dorepairownership = 1;
    print "### ${PROGNAME}: Initializing TeX (please wait) ...\n";
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/texmf.local/web2c/*.fmt");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/texmf.local/web2c/*/*.fmt");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/texmf.local/web2c/*.log");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/texmf.local/web2c/*/*.log");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/texmf.local/web2c/*.?fmt");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/texmf.local/web2c/*.oft");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/texmf.local/web2c/*.mem");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/texmf.local/web2c/*.base");
    # Do pdflatex and latex first so they are not created by mktexfmt
    # for formats that depend on them to exist (tip by Thomas Esser)
    # Not doing this has lead to endless loops in fmtutil in the past
    ipkgsystem( "${fmtutilcmd} --byfmt latex </dev/null");
    ipkgsystem( "${fmtutilcmd} --byfmt pdflatex </dev/null");
    ipkgsystem( "${fmtutilcmd} --all </dev/null");
    my $texmfvardir;
    if (defined $configforuser and $configforuser ne 'root') {
	$texmfvardir = `kpsewhich -var-value=TEXMFVAR`;
	if (not defined $texmfvardir) {
	    $texmfvardir = `kpsewhich -var-value=TEXMFLOCAL`;
	}
	chomp( $texmfvardir);
	ipkgsystem( "/usr/bin/env TEXFORMATS=\"${texmfvardir}/web2c\" texexec --xetex --make --all --fast en</dev/null");
	ipkgsystem( "/usr/bin/env TEXFORMATS=\"${texmfvardir}/web2c\" texexec --xetex --make --all --fast nl</dev/null");
	ipkgsystem( "/usr/bin/env TEXFORMATS=\"${texmfvardir}/web2c\" texexec --make --all --fast</dev/null");
    }
    else {
	my $sudostring = "sudo -H -u root";
	$texmfvardir = `${sudostring} kpsewhich -var-value=TEXMFSYSVAR`;
	if (not defined $texmfvardir) {
	    $texmfvardir = `kpsewhich -var-value=TEXMFLOCAL`;
	}
	chomp( $texmfvardir);
	ipkgsystem( "${sudostring} /usr/bin/env TEXFORMATS=\"${texmfvardir}/web2c\" texexec --xetex --make --all --fast en</dev/null");
	ipkgsystem( "${sudostring} /usr/bin/env TEXFORMATS=\"${texmfvardir}/web2c\" texexec --xetex --make --all --fast nl</dev/null");
	ipkgsystem( "${sudostring} /usr/bin/env TEXFORMATS=\"${texmfvardir}/web2c\" texexec --make --all --fast</dev/null");
    }
    
    ipkgsystem( "texlinks --silent </dev/null");
    `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t SetConfiguredSelectorSets -P "${tlversion}-bin-${arch}|${tlversion}-texmfe"`;
}

sub updateFontMappings
{
    # Configure Latin Modern, this implies making sure the map files have been activated
    lmConfig();

    $updmapcfgloc = `${kpsewhichcmd} --format='web2c files' updmap.cfg`;
    if ($updmapcfgloc eq '') {
	die "### ${PROGNAME}: updmap.cfg is missing. Bailing out...\n";
    }

    if (ipkgsystem( 'updmap --help 2>&1 </dev/null | grep "syncwithtrees" >/dev/null 2>&1') == 0) {
	print "### ${PROGNAME}: Executing updmap --syncwithtrees\n";
	ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --syncwithtrees 2>&1 </dev/null');
    }

    my $updmaplistcmd = '--listmaps';

    REDOMAPPINGS:
    $selections = undef;
    %map = undef;
    if (open( MAPS, "${updmapcmd} " . "$updmaplistcmd 2>/dev/null |")) {
	while (<MAPS>) {
	    $status = '+';
	    if (s/^#!\s*//) {
		$status = '-';
	    }
	    if (/^((Mixed)?Map)\s(\S+)/) {
		$map{$3} = "$status$1";
		$selections .= "$status$3|";
	    }
	}
	close( MAPS);
	chop( $selections);
	$doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Select -C \"$selections\"  -T "(De)Activate maps" -I "Select maps you want to activate or deactivate. Note: Not all shown maps need to be available on your system. If they are not available they will be silently deactivated again." -1 "Select" -2 "Add One" -3 "Cancel"`;
	chomp( $doresult);
	if (($? >> 8) == 0) {
	    $dorepairownership = 1;
	    @newmappings = split( /\|/, $doresult);
	    $dorunupdmap = 1; # always do this on Select
	    foreach my $newmap (@newmappings) {
		($newstatus,$mapname) = $newmap =~ /([-+])(.+)/;
		($oldstatus,$maptype) = $map{$mapname} =~ /([-+])(.+)/;
		if ($oldstatus ne $newstatus) {
		    if ($newstatus eq '+') {
			print "### ${PROGNAME}: Enabling $mapname ($maptype)\n";
			ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable $maptype $mapname >/dev/null 2>&1 </dev/null");
		    }
		    else {
			print "### ${PROGNAME}: Disabling $mapname\n";
			ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --disable $mapname >/dev/null 2>&1 </dev/null");
		    }
		}
	    }
	}
	elsif (($? >> 8) == 1) {
	    print "### ${PROGNAME}: Keeping current map settings.\n";
	}
	elsif (($? >> 8) == 2) {
	    warn "### ${PROGNAME}: Add map not implemented yet.\n";
	    goto REDOMAPPINGS;
	}
	$doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Configure for full font inclusion?" -I "TeX can be configured to include all standard fonts in your output. Normally this is not necessary because these fonts are, um, standard and they are available everywhere. However, some publishers require a full font inclusion for the documents you produce. Your documents will become pretty large so do not do this unless it is really required.\n\nChoose \\\"No Include\\\" when in doubt." -1 "No Include" -2 "Include" -3 "No Change"`;
	chomp( $doresult);
	if (($? >> 8) == 0) {
	    print "### ${PROGNAME}: updmap font inclusion settings set to false (default).\n";
	    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --setoption dvipsDownloadBase35 false 2>&1 </dev/null");
	    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --setoption pdftexDownloadBase14 false 2>&1 </dev/null");
	    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --setoption dvipdfmDownloadBase14 false 2>&1 </dev/null");
	    $dorunupdmap = 1;
	}
	elsif (($? >> 8) == 2) {
	    print "### ${PROGNAME}: updmap font inclusion settings set to true.\n";
	    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --setoption dvipsDownloadBase35 true 2>&1 </dev/null");
	    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --setoption pdftexDownloadBase14 true 2>&1 </dev/null");
	    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --setoption dvipdfmDownloadBase14 true 2>&1 </dev/null");
	    $dorunupdmap = 1;
	}
    }
    else {
	warn "### ${PROGNAME}: Unable to get list of known maps from updmap.cfg\n";
    }
}

sub setOwner
{
    if (open( PASSWD, "nidump passwd .|")) {
	my $userselect = undef;
	my %unameforrealname = undef;
	while (<PASSWD>) {
	    ($uname,$passwd,undef,undef,undef,undef,undef,$realname,$dir,$shell) =
		split( /:/);
	    if ($uname eq 'root' or ($passwd ne '*' and -d $dir and
		$shell =~ /\/(tcsh|sh|bash|zsh|ksh)$/)) {
		$realname =~ tr [\200-\377][\000-\177]; # Hack. Or accented names do not work when they are passed to/from doalerter
		$userselect .= "$realname|";
		$unameforrealname{"$realname"} = $uname;
	    }
	}
	close( PASSWD);
	chop( $userselect);
	$doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Choice -T "Select User" -C "$userselect" -I "Please select the user who will own TeX on this system. The default is the System Administrator or root user" -1 "Set" -2 "Default" -3 "No Change"`;
	chomp( $doresult);
	if (($? >> 8) == 0) {
	    $realname = "$doresult";
	}
	elsif (($? >> 8) == 2) {
	    $realname = 'System Administrator';
	}
	else {
	    print "### ${PROGNAME}: Keeping current ownership of the TeX installation.\n";
	    $realname = undef;
	}
	if (defined $realname) {
	    $dorepairownership = 0;
	    $uname = $unameforrealname{"$realname"};
	    my (undef,undef,undef,$gid,undef,undef,undef,undef) = getpwnam( $uname); # Get gid of user
	    my $gname = getgrgid( $gid);
	    print "### ${PROGNAME}: Setting ownership of TeX installation in ${II2INSTALLDIR} to $realname ($uname). Please wait...\n";
	    ipkgsystem( "/usr/sbin/chown -R \"${uname}:${gname}\" ${II2INSTALLDIR}") == 0
		or die "### ${PROGNAME}: failed to run chown -R \"${uname}:${gname}\". Bailing out...\n";;
	}
    }
    else {
	warn "### ${PROGNAME}: Unable to get list of local users\n";
    }
}

sub checkPersonalConfigs
{
    if (open( PASSWD, "nidump passwd .|")) {
	my $userselect = undef;
	while (<PASSWD>) {
	    ($uname,$passwd,undef,undef,undef,undef,undef,$realname,$dir,$shell) =
		split( /:/);
	    if ($uname eq 'root' or ($passwd ne '*' and -d $dir and
		$shell =~ /\/(tcsh|sh|bash|zsh|ksh)$/)) {
		$realname =~ tr [\200-\377][\000-\177]; # Hack. Or accented names do not work when they are passed to/from doalerter
		if (-e "$dir/Library/texmf/tex/generic/config/language.dat" or
		    -e "$dir/Library/texmf/web2c/updmap.cfg" or
		    -e "$dir/Library/texmf/web2c/fmtutil.cnf" or
		    -e "$dir/Library/texmf/fonts/map/pdftex/updmap/pdftex.map") {
		    $userselect .= "$realname, ";
		}
	    }
	}
	close( PASSWD);
	$userselect =~ s/, $//;
	if ($userselect ne "") {
	    `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Warning: Personal User configuration(s)" -I "I found (a) personal configuration file(s) for user(s): ${userselect}. These users will not fully use system-wide settings and their TeX configuration is not fully covered by this system-wide configuration phase." -1 "Proceed"`;
	}
    }
    else {
	warn "### ${PROGNAME}: Unable to get list of local users\n";
    }
}

sub lmConfig
{
    print "### ${PROGNAME}: Preparing TeX for Latin Modern configuration...\n";
    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --disable lm-ec.map </dev/null");
    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --disable lm-qx.map </dev/null");
    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --disable lm-texnansi.map </dev/null");
    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --disable lm-ts1.map </dev/null");
    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --disable lm-t5.map </dev/null");
    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map lm.map </dev/null");
    ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map lm-math.map </dev/null");
}

sub macFontUnpacking
{
    print "### ${PROGNAME}: Attempting to unpack Mac fonts for TeX use...\n";
    my $macfontdir = "/Library/Fonts";
    my $makeafms = 0;

    if (not -x "/usr/local/bin/fondu") {
	print "### ${PROGNAME}: Fondu is not available. I will not unpack Mac fonts.\n";
	return;
    }
    else {
	print "### ${PROGNAME}: Fondu is available. Checking for missing unpacked fonts...\n";
    }
    if (not -x "/usr/local/bin/fontforge") {
	print "### ${PROGNAME}: FontForge is not available. I will not generate AFMs.\n";
    }
    else {
	print "### ${PROGNAME}: FontForge is available. I will create AFMs.\n";
	$makeafms = 1;
    }
    my $dohash = 0;
    my %fonttable = ( "gillsans", "/Library/Fonts/GillSans.dfont",
		      "optima", "/Library/Fonts/Optima.dfont",
		      "hoefler", "/Library/Fonts/Hoefler Text.dfont",
		      "didot", "/Library/Fonts/Didot.dfont",
		      "baskerville", "/Library/Fonts/Baskerville.dfont",
		      "americantypewriter", "/Library/Fonts/AmericanTypewriter.dfont",
		      "futura", "/Library/Fonts/Futura.dfont",
		      "lucidagrande", "/System/Library/Fonts/LucidaGrande.dfont",
		      "verdana", "/Library/Fonts/Verdana",
		      "georgia", "/Library/Fonts/Georgia",
		      "helveticaneue", "/Library/Fonts/HelveticaNeue.dfont"
    );
    foreach my $texname (keys %fonttable) {
	my $macfontfile = $fonttable{$texname};
	if (not -d "${II2INSTALLDIR}/texmf.gwtex/fonts/truetype/gtamacfonts/${texname}") {
	    print "### ${PROGNAME}: running Fondu on \"${macfontfile}\".\n";
	    ipkgsystem( "/bin/mkdir -p \"${II2INSTALLDIR}/texmf.gwtex/fonts/truetype/gtamacfonts/${texname}\" && " .
			"cd \"${II2INSTALLDIR}/texmf.gwtex/fonts/truetype/gtamacfonts/${texname}\" && " .
			"/usr/local/bin/fondu \"${macfontfile}\"") == 0
		or warn "### ${PROGNAME}: failed to run Fondu on \"${macfontfile}\".\n";
	    $dohash = 1;
	}
	else {
	    print "### ${PROGNAME}: \"${macfontfile}\" has already been made available to TeX as separate files.\n";
	}
	if (not -d "${II2INSTALLDIR}/texmf.gwtex/fonts/afm/gtamacfonts/${texname}") {
	    print "### ${PROGNAME}: running FontForge on \"${macfontfile}\".\n";
	    ipkgsystem( "/bin/mkdir -p \"${II2INSTALLDIR}/texmf.gwtex/fonts/afm/gtamacfonts/${texname}\" && " .
			"cd \"${II2INSTALLDIR}/texmf.gwtex/fonts/afm/gtamacfonts/${texname}\" && " .
			"/usr/local/bin/fontforge -script \"${II2PKGDIR}/dumpafm.pe\" \"${macfontfile}\"") == 0
		or warn "### ${PROGNAME}: failed to run FontForge on \"${macfontfile}\".\n";
	    $dohash = 1;
	}
	else {
	    print "### ${PROGNAME}: \"${macfontfile}\" has already been made available as AFMs.\n";
	}
    }
    if ($dohash) {
	print "### ${PROGNAME}: updating TeX hash of \"${II2INSTALLDIR}/texmf.gwtex\", please wait...\n";
	ipkgsystem( "mktexlsr \"${II2INSTALLDIR}\"/texmf.gwtex") == 0
	    or warn "### ${PROGNAME}: failed to run mktexlsr on texmf.gwtex.\n";
    }
}

sub lmFontInstallation
{
    print "### ${PROGNAME}: Latin Modern fonts will be installed for GUI use.\n";
    my $macfontdir = "/Library/Fonts/Latin Modern";
    if (not -d $macfontdir) {
	ipkgsystem( "/bin/mkdir -p \"${macfontdir}\"");
    }
    if (-d $macfontdir) {
	ipkgsystem( "/bin/rm -f \"${macfontdir}\"/*");
	my $lmotfdir = "${II2INSTALLDIR}/texmf.texlive/fonts/opentype/public/lm";
	ipkgsystem( "/bin/cp \"${lmotfdir}\"/*  \"$macfontdir\"");
    }
    else {
	warn "### ${PROGNAME}: Subroutine lmFontInstallation() needs the /Library/Fonts/Latin Modern directory to exist.\n";
    }
}

sub do_updmap
{
    print "### ${PROGNAME}: Removing old updmap results. Please wait...\n";
    my $vartexmf;
    if (defined $configforuser and $configforuser ne 'root') {
	$vartexmf = `kpsewhich --expand-var=\'\$HOMETEXMF\'`;
    }
    else {
	$vartexmf=`sudo -H -u root kpsewhich --expand-var=\'\$VARTEXMF\'`;
    }
    chomp( $vartexmf);
    foreach my $file (('dvipdfm.map', 'dvipdfm_dl14.map', 'dvipdfm_ndl14.map',
		       'builtin35.map', 'download35.map', 'ps2pk.map',
		       'psfonts.map', 'psfonts_pk.map', 'psfonts_t1.map',
		       'pdftex.map', 'pdftex_dl14.map', 'pdftex_ndl14.map')) {
	my $cmd = "find \"$vartexmf\" " . '-name ' . $file . ' -exec rm -f {} \; 2>&1 </dev/null';
	print "### ${PROGNAME}: Executing $cmd\n";
	ipkgsystem( $cmd);
    }

    if (ipkgsystem( "${updmapcmd} " . '--help 2>&1 </dev/null | grep "syncwithtrees" >/dev/null 2>&1') == 0) {
	ipkgsystem( "${updmapcmd} " . '--nohash --syncwithtrees --nomkmap 2>&1 </dev/null');
    }
    ipkgsystem( "${updmapcmd} " . '--nohash 2>&1 </dev/null');
    if (-e "${vartexmf}/ls-R") {
	if (not defined $configforuser or $configforuser eq 'root') {
	    ipkgsystem( "sudo -H -u root texhash \"${vartexmf}\"");
	}
	else {
	    ipkgsystem( "texhash \"${vartexmf}\"");
	}
    }
}

# $Id: tex.configure 71 2006-10-09 19:46:02Z gctwnl $

