#!/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'}";

setConfigUser();

# Load shared stuff
if (not -e "${II2PKGDIR}/tex.sharedscript.pm") {
    my $msg = "A part of the package is missing. This might be a known bug in i-Installer 2.69 or older. Please reset your package to its default properties before trying again. You can do that with the Reset to default properties menu item in the i-Package menu.\n\nIf the problem remains, the problem is a network problem, not an i-Installer bug.\n\nThis action will now fail deliberately.";
    warn "### ${PROGNAME}: ${msg}";
    `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Missing part/known bug" -I "${msg}" -1 "Accept"`;
    exit 1;
}
require "${II2PKGDIR}/tex.sharedscript.pm";

if (not $ENV{'TEXIPKGUSDEPRECATED'} eq 'YES') {
    if (not -e "/usr/local/gwTeX") {
	ipkgwarn( "This i-Package is deprecated and no longer maintained as one of its components (the teTeX main texmf tree) is no longer maintained.\n\nThe i-Package is kept alive for people who require an older TeX install for compatibility with old projcts.\n\nThere is a new gwTeX i-Package which is not based in part on teTeX but based on a subset of TeX Live. Please migrate.\n");
    }
    else {
	my $msg = "You are now using the deprecated gwTeX-2003-2005 i-Package partly based on teTeX. This i-Package is deprecated and no longer maintained.\n\nYou already seem to have gwTeX based on a subset of TeX Live installed.\n\nI suggest uninstalling this i-Package unless you need access to a TeX based on the 2003 situation.\n";
	$doresult = `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "Are you sure you want to use this i-Package?" -I \"${msg}\" -1 "Yes" -2 "No"`;
	chomp( $doresult);
	if (($? >> 8) != 0) {
	    warn "i-Package process aborted at user request\n";
	    exit 0;
	}
    }
}

#
$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);
}

# What structure do we expect? TL2003 or TL2004?
my $tlversion;	    # Set in checkPrerequisites()
my $dorunupdmap = 0;    # Single updmap run
checkPrerequisites();

if ($tlversion =~ /tl200[45]/) {
    warn "### ${PROGNAME}: Making sure texmf.local conforms to TL2004+ format. Please wait...\n";
    `/usr/bin/ruby "${II2INSTALLDIR}"/share/texmf.tetex/scripts/context/ruby/textools.rb --fixtexmftrees --force \`kpsewhich --var-value TEXMFLOCAL\``;
}

`"${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 $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}/share/texmf.local/tex/generic/context") {
    my $doremovelocalcontext = 0;
    # More recent versions use \edef instead of \def
    my $localversion = `grep '\\\\e\\?def\\\\contextversion' "${II2INSTALLDIR}/share/texmf.local/tex/context/base/context.tex"`;
    chomp( $localversion);
    my $tetexversion = `grep '\\\\e\\?def\\\\contextversion' "${II2INSTALLDIR}/share/texmf.tetex/tex/context/base/context.tex"`;
    chomp( $tetexversion);
    $localversion =~ s/^.*\\e?def\\contextversion\{//;
    $localversion =~ s/\}.*$//;
    $tetexversion =~ s/^.*\\e?def\\contextversion\{//;
    $tetexversion =~ s/\}.*$//;

    if ($simpleinstall) {
	$doremovelocalcontect = 1 if ($localversion le $tetexversion);
    }
    else {
	if ($localversion gt $tetexversion) {
	    my $msg = "I recommend keeping it because it is newer ($localversion) than the version in the teTeX tree ($tetexversion)";
	    $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;
	    }
	}
	else {
	    my $msg = "I recommend removing it because it is out of date ($localversion) with respect to the version in the teTeX tree ($tetexversion)";
	    $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;
	    }
	}
    }
    if ($doremovelocalcontext) {
	print "### ${PROGNAME}: Removing texmf.local ConTeXt. Please wait...\n";

	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/metapost/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/tex/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/tex/generic/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/tex/latex/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/context/data\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/context/config\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/context/examplap\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/doc/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/scripts/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/fonts/enc/dvips/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/fonts/enc/pftex/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/fonts/map/dvips/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/fonts/map/pftex/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/doc/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/pdftex/config/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/fonts/tfm/hoekwater/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/fonts/type1/hoekwater/context\"");
	ipkgsystem( "/bin/rm -rf \"${II2INSTALLDIR}/share/texmf.local/web2c/natural.tcx\"");
	unlink "${II2INSTALLDIR}/share/texmf.local/dvips/config/context.map";
	ipkgsystem( "texhash \"${II2INSTALLDIR}/share/texmf.local\"");
    }
    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)
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;
}

`"${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{'gwtex23'})) {
    if ($set{'gwtex23'}{'installed'} eq 'YES') {
	if ($set{'gwtex23'}{'configured'} eq 'NO') {
	    print "### ${PROGNAME}: Enabling map files for gwTeX additions. This is a slow process. Please wait....\n";

	    my $foundrelsymb = 0;
	    my $foundyfrak = 0;
	    my $foundtipa = 0;
	    my $founddictsym = 0;
	    my $foundgtamacfonts = 0;
	    my $foundcjhebrew = 0;
	    my $foundutopia = 0;
	    my $foundfourier = 0;
	    my $foundfourierexpert = 0;

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

	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "^Map fourier-utopia-expert.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Found fourier-utopia-expert.map for commercial fonts\n";
		$foundfourierexpert = 1;
	    }
	    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 "^MixedMap yfrak.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Found yfrak.map\n";
		$foundyfrak = 1;
	    }
	    else {
		print "### ${PROGNAME}: Enabling yfrak.map\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable MixedMap yfrak.map >/dev/null 2>&1 </dev/null');
		$dorunupdmap = 1;
	    }
	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "^MixedMap tipa.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Found tipa.map\n";
		$foundtipa = 1;
	    }
	    else {
		print "### ${PROGNAME}: Enabling tipa.map\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable MixedMap tipa.map >/dev/null 2>&1 </dev/null');
		$dorunupdmap = 1;
	    }
	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "^Map dictsym.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Found dictsym.map\n";
		$founddictsym = 1;
	    }
	    else {
		print "### ${PROGNAME}: Enabling dictsym.map\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map dictsym.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;
	    }
	    else {
		print "### ${PROGNAME}: Enabling gtamacfonts.map\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map gtamacfonts.map >/dev/null 2>&1 </dev/null');
		$dorunupdmap = 1;
	    }
	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "^Map cjhebrew.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Found cjhebrew.map\n";
		$foundcjhebrew = 1;
	    }
	    else {
		print "### ${PROGNAME}: Enabling cjhebrew.map\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map cjhebrew.map >/dev/null 2>&1 </dev/null');
		$dorunupdmap = 1;
	    }
	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 <dev/null | grep "^Map utopia.map" >/dev/null 2>&1') == 0) {
		print "### ${PROGNAME}: Found utopia.map\n";
		$foundutopia = 1;
	    }
	    else {
		if (not $foundfourierexpert) {
		    print "### ${PROGNAME}: Enabling utopia.map\n";
		    ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map utopia.map >/dev/null 2>&1 </dev/null');
		    $dorunupdmap = 1;
		}
	    }
	    if (ipkgsystem( "${updmapcmd} " . $updmaplistcmd . ' 2>&1 </dev/null | grep "^Map fourier.map" >/dev/null') == 0) {
		print "### ${PROGNAME}: Found fourier.map\n";
		$foundfourier = 1;
	    }
	    if (not $foundfourierexpert and not $foundfourier) {
		print "### ${PROGNAME}: Enabling fourier.map\n";
		ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --enable Map fourier.map >/dev/null 2>&1 </dev/null');
		$dorunupdmap = 1;
	    }
	    `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t SetConfiguredSelectorSets -P "gwtex23"`;
	    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";
	}
	macFontUnpacking();
    }
    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 yfrak.map >/dev/null 2>&1 </dev/null');
	ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable tipa.map >/dev/null 2>&1 </dev/null');
	ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable dictsym.map >/dev/null 2>&1 </dev/null');
	ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable cjhebrew.map >/dev/null 2>&1 </dev/null');
	ipkgsystem( "${updmapcmd} " . '--nohash --nomkmap --disable fourier.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 50000`;

# Configure tex4ht, this implies installing and setting up tex4ht.env and
# installing the mk4ht script
if (exists( $set{'tex4ht'}) and
    $set{'tex4ht'}{'installed'} eq 'YES' and
    $set{'tex4ht'}{'configured'} ne 'YES') {
    print "### ${PROGNAME}: TeX4ht support has been installed but not yet configured.\n";
    tex4htConfig();
}

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

# Configure Latin Modern, this implies installing and setting up map files
lmConfig();
`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t IncrementProgress -p 10000`;

my $createverb = (-d "/Library/Fonts/Latin Modern") ? "recreate" : "create";
if (not $simpleinstall) {
    my $msg = (${createverb} eq "create" ? "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 convert them? Conversion requires a FontForge installation.";
    $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 "create")) or
    (not $simpleinstall and ($? >> 8) == 0)) {
    lmFontConversion();
}

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


# Configure xmljadetex
if (exists( $set{'xmljadetex'}) and
    $set{'xmljadetex'}{'installed'} eq 'YES' and
    $set{'xmljadetex'}{'configured'} ne 'YES') {
    print "### ${PROGNAME}: XMLTeX/JadeTeX support has been installed but not yet configured.\n";
    xmlJadeTeXConfig();
}

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

# re-create symlink if necessary:
$TEXNAME = `/usr/bin/basename "${II2INSTALLDIR}"`;
chomp( ${TEXNAME});
my $tmpreldir = "${II2INSTALLDIR}";
$tmpreldir =~ s/^\///;
my $reldir = '../../' . $tmpreldir;
if (not -e "/Library/${TEXNAME}" ) {
    print "### ${PROGNAME}: Creating /Library/${TEXNAME} symbolic link  as \"${reldir}\"...\n";
    symlink( "${reldir}", "/Library/${TEXNAME}") or warn "### ${PROGNAME}: Unable to create /Library/${TEXNAME} existing symbolic link";
}
elsif ( -l "/Library/${TEXNAME}" ) {
    print "### ${PROGNAME}: Recreating /Library/${TEXNAME} symbolic link  as \"${reldir}\"...\n";
    unlink( "/Library/${TEXNAME}") or warn "### ${PROGNAME}: Unable to remove /Library/${TEXNAME} existing symbolic link";
    symlink( "${reldir}", "/Library/${TEXNAME}") or warn "### ${PROGNAME}: Unable to recreate /Library/${TEXNAME} existing symbolic link";
}
else {
    warn "### ${PROGNAME}: /Library/${TEXNAME} exists and is not a symbolic link. I am leaving it alone.";
}

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

# 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 ($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";
    if (ipkgsystem( "\"${II2PKGDIR}/\"settexpath \"${II2INSTALLDIR}\" remove") == 0) {
	print "### ${PROGNAME}: sucessfully removed any CLI path settings.\n";
    }
    if (ipkgsystem( "\"${II2PKGDIR}/\"settexpath \"${II2INSTALLDIR}\"") == 0) {
	print "### ${PROGNAME}: sucessfully (re-)added CLI path settings.\n";
    }
    else {
	warn "### ${PROGNAME}: failed to add CLI 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 (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 xmlJadeTeXConfig
{
    my $fmtutilloc=`${kpsewhichcmd} --format='web2c files' fmtutil.cnf`;
    chomp( $fmtutilloc);

    ipkgsystem( "egrep '^latex[[:space:]]+etex[[:space:]]' \"$fmtutilloc\" >/dev/null 2>&1");
    if (($? >> 8) == 0) {
	$etexlatex = 1;
    }
    else {
	warn "### ${PROGNAME}: fmtutil.cnf contains non-ETeX LaTeX.\n" if $tlversion eq "tl2003";
	$etexlatex = 0;
    }

    if (ipkgsystem( "grep pdfjadetex \"${fmtutilloc}\" >/dev/null 2>&1") != 0) {
	print "### ${PROGNAME}: Adding jadetex entries to ${fmtutilloc}\n";
	open( FMTUTIL, ">>${fmtutilloc}") or die "### ${PROGNAME}: Cannot append to ${fmtutilloc}\n";
	print FMTUTIL "\n### Added by jadetex i-Package configuration.\n### Do not remove previous line\n";
	if ($etexlatex) {
	    print FMTUTIL "xmltex\t\tetex\tlanguage.dat\t&latex xmltex.ini\n";
	    print FMTUTIL "pdfxmltex\tpdfetex\tlanguage.dat\t&pdflatex pdfxmltex.ini\n";
	    print FMTUTIL "jadetex\t\tetex\tlanguage.dat\t&elatex jadetex.ini\n";
	    print FMTUTIL "pdfjadetex\tpdfetex\tlanguage.dat\t&pdfelatex jadetex.ini\n";
	}
	else {
	    print FMTUTIL "xmltex\t\tetex\tlanguage.dat\t&elatex xmltex.ini\n";
	    print FMTUTIL "pdfxmltex\tpdfetex\tlanguage.dat\t&pdfelatex pdfxmltex.ini\n";
	    print FMTUTIL "jadetex\t\tetex\tlanguage.dat\t&latex jadetex.ini\n";
	    print FMTUTIL "pdfjadetex\tpdfetex\tlanguage.dat\t&pdflatex jadetex.ini\n";
	}
	print FMTUTIL "### Do not remove next line\n### Added by jadetex i-Package configuration.\n";
	close FMTUTIL;
    }

    ipkgsystem( "${fmtutilcmd} --enablefmt xmltex </dev/null");
    ipkgsystem( "${fmtutilcmd} --enablefmt pdfxmltex </dev/null");
    ipkgsystem( "${fmtutilcmd} --enablefmt jadetex </dev/null");
    ipkgsystem( "${fmtutilcmd} --enablefmt pdfjadetex </dev/null");

    warn "### ${PROGNAME}: Force creation of formats because fmtutil.cfg may have changed." if $docreateformats == 0;
    $docreateformats=1;

    $texmfcnfloc=`${kpsewhichcmd} --format='web2c files' texmf.cnf`;
    chomp( $texmfcnfloc);
    $main_memory_pdfjadetex = `${kpsewhichcmd} -progname=pdfjadetex -expand-var=\'\$main_memory\'`;
    chomp( $main_memory_pdfjadetex);
    $main_memory_pdfjadetex =~ s/^(\w+).*$/\1/;
    $main_memory_jadetex = `${kpsewhichcmd} -progname=jadetex -expand-var=\'\$main_memory\'`;
    chomp( $main_memory_jadetex);
    $main_memory_jadetex =~ s/^(\w+).*$/\1/;

    if (not defined $main_memory_pdfjadetex or $main_memory_pdfjadetex < 2500000) {
	warn "### ${PROGNAME}: The texmf.cnf main_memory.pdfjadetex is too small ($main_memory_pdfjadetex).\n";
	warn "### ${PROGNAME}: Adding main_memory.pdfjadetex = 2500000 to texmf.cnf.\n";
	warn "### ${PROGNAME}: You may need to re-run the configuration when you update TeX Programs only\n";
	open( TEXMFCNF, ">>${texmfcnfloc}") or die "### ${PROGNAME}: Cannot append to ${fmtutilloc}\n";
	print TEXMFCNF "\n%%% Added by jadetex i-Package configuration.\n%%% Do not remove previous line\n";
	print TEXMFCNF "main_memory.pdfjadetex = 2500000\n";
	print TEXMFCNF "%%% Do not remove next line\n%%% Added by jadetex i-Package configuration.\n";
	close TEXMFCNF;
    }
    if (not defined $main_memory_jadetex or $main_memory_jadetex < 2000000) {
	warn "### ${PROGNAME}: The texmf.cnf main_memory.jadetex is too small ($main_memory_jadetex).\n";
	warn "### ${PROGNAME}: Adding main_memory.jadetex = 2000000 to texmf.cnf.\n";
	warn "### ${PROGNAME}: You may need to re-run the configuration when you update TeX Programs\n";
	open( TEXMFCNF, ">>${texmfcnfloc}") or die "### ${PROGNAME}: Cannot append to ${fmtutilloc}\n";
	print TEXMFCNF "\n%%% Added by jadetex i-Package configuration.\n%%% Do not remove previous line\n";
	print TEXMFCNF "main_memory.jadetex = 2000000\n";
	print TEXMFCNF "%%% Do not remove next line\n%%% Added by jadetex i-Package configuration.\n";
	close TEXMFCNF;
    }

#    print "### ${PROGNAME}: Creating formats. Please wait...\n";
#    ipkgsystem( "${fmtutilcmd} --byfmt xmltex </dev/null");
#    ipkgsystem( "${fmtutilcmd} --byfmt pdfxmltex </dev/null");
#    ipkgsystem( "${fmtutilcmd} --byfmt jadetex </dev/null");
#    ipkgsystem( "${fmtutilcmd} --byfmt pdfjadetex </dev/null");
    `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t SetConfiguredSelectorSets -P "xmljadetex"`;
}

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 = 0;
	$doselectlanguages = 0;
	$docreateformats = 1;
	$dopapersizeselection = 1;
	$doupdatefontmappings = 0;
	$doownerselection = 0;
	$docliactivation = 1;
	$dorepairownership = 1;
	$dohometexactivation = 0;
	return;
    }
    my $choiceString;

    $choiceString = "-Formats Selection|+Languages Selection|";
    if ((exists( $set{'tl2003-bin-powerpc'}) and not
	 ($set{'tl2003-bin-powerpc'}{'configured'} eq 'YES')) or
	(exists( $set{'tl2004-bin-${arch}'}) and not
	 ($set{'tl2004-bin-${arch}'}{'configured'} eq 'YES')) or
	(exists( $set{'tl2005-bin-${arch}'}) and not
	 ($set{'tl2005-bin-${arch}'}{'configured'} eq 'YES')) or
	(exists( $set{'tetex2-texmfe'}) and not
	 ($set{'tetex2-texmfe'}{'configured'} eq 'YES')) or
	(exists( $set{'tetex3-texmfe'}) and not
	 ($set{'tetex3-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|-Update Font Mappings|-TeX Owner Selection|+CLI Activation|+Personal Config Activation"
    }
    else {
	$choiceString .= "-Formats Creation|+Paper Size Selection|-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/;
	$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 = ($tlversion eq 'tl2003' ?
			   -f "${II2INSTALLDIR}/share/texmf.local/web2c/pdflatex.efmt" :
			   -f "${II2INSTALLDIR}/share/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;
	$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}/share/texmf/web2c/pdfetex.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);
    }
    else {
	# What structure do we expect? TL2003 or TL2004?
	$tlversion = (-f "${II2INSTALLDIR}/share/texmf/web2c/aleph.pool" and not
		      -f "${II2INSTALLDIR}/share/texmf/web2c/etex.pool") ?
	    "tl2004" : "tl2003";
	print "### ${PROGNAME}: Detected ${tlversion}-type structure.\n";
    }
    if (not -e "${II2INSTALLDIR}/share/texmf.tetex/ChangeLog") {
	warn "### ${PROGNAME}: No (complete) TeX Foundation 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 Foundation now.\n";
	warn "### ${PROGNAME}: Bailing out gracefully...\n";
	`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t Alert -T "TeX Foundation Unavailable" -I "TeX cannot be configured because the TeX Foundation has not been installed yet. Or you are using a nother layout, in which case you need to configure from the command line. Only when both foundation and programs have been installed (in either order) will the configuration script proceeed. Just install TeX Foundation now." -1 "OK"`;
	exit( 0);
    }

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

    if ( ! -e "${II2INSTALLDIR}/texmf.cnf" ) {
	print "### ${PROGNAME}: ${II2INSTALLDIR}/texmf.cnf does not exist. Creating default.\n";
	ipkgsystem( "cp \"${II2PKGDIR}/texmf.cnf.gwtex.${tlversion}\" \"${II2INSTALLDIR}/texmf.cnf\"") == 0
	    or die "### ${PROGNAME}: failed to install new texmf.cnf. Bailing out...\n";
    }
    elsif ( ipkgsystem( "/usr/bin/cmp -s \"${II2INSTALLDIR}/texmf.cnf\" \"${II2PKGDIR}/texmf.cnf.gwtex.${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.gwtex.${tlversion}\"");
	ipkgsystem( "mv \"${II2INSTALLDIR}/texmf.cnf\" \"${II2INSTALLDIR}/${previoustexmfcnf}\"" );
	ipkgsystem( "cp \"${II2PKGDIR}/texmf.cnf.gwtex.${tlversion}\" \"${II2INSTALLDIR}/texmf.cnf\"") == 0
	    or die "### ${PROGNAME}: failed to install new texmf.cnf. Bailing out...\n";
    }

    if ( ! -w "${II2INSTALLDIR}/share/texmf.local" or ! -d "${II2INSTALLDIR}/share/texmf.local" ) {
	warn "### ${PROGNAME}: ${II2INSTALLDIR}/share/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}/share/texmf.tetex/dvipdfm/config" and  -f "${II2INSTALLDIR}/share/texmf.local/dvipdfm/config" ) {
	warn "### ${PROGNAME}: ${II2INSTALLDIR}/share/texmf.local/dvipdfm/config is not a directory while the one from teTeX is. Adapting...\n";
	ipkgsystem( "mv \"${II2INSTALLDIR}/share/texmf.local/dvipdfm/config\" \"${II2INSTALLDIR}/share/texmf.local/dvipdfm/config.temp\"") == 0
	    or die "### ${PROGNAME}: failed to temporarily move dvipdfm/config. Bailing out...\n";
	ipkgsystem( "mkdir \"${II2INSTALLDIR}/share/texmf.local/dvipdfm/config\"") == 0
	    or die "### ${PROGNAME}: failed to create dvipdfm/config directory. Bailing out...\n";
	ipkgsystem( "mv \"${II2INSTALLDIR}/share/texmf.local/dvipdfm/config.temp\" \"${II2INSTALLDIR}/share/texmf.local/dvipdfm/config/config\"") == 0
	    or die "### ${PROGNAME}: failed to move config file into new dvipdfm config dir. Bailing out...\n";
    }

    # Check is texconfig is recent enough if not install a new one
    # and run a localsetup
    ipkgsystem( "texconfig help </dev/null 2>&1 | grep '\\(localsetup\\|font ro\\)' >/dev/null");
    if (($? >> 8) != 0) {
	$dorepairownership = 1;
	print "### ${PROGNAME}: This TeX does not have a recent texconfig. Installing one...\n";
	$texconfigloc = `which texconfig`;
	chomp( $texconfigloc);
	ipkgsystem( "cp \"${II2PKGDIR}/texconfig.${tlversion}\" \"$texconfigloc\"") == 0
	    or die "### ${PROGNAME}: failed to install \"${II2PKGDIR}/texconfig.${tlversion}\" as \"$texconfigloc\". Bailing out...\n";
    }
    ipkgsystem( "texconfig help </dev/null 2>&1 | grep 'localsetup' >/dev/null");
    if (($? >> 8) == 0) {
	print "### ${PROGNAME}: Creating a local setup for texconfig...\n";
	ipkgsystem( "texconfig localsetup </dev/null");
	if (($? >> 8) != 0) {
	    warn "### ${PROGNAME}: Failed to run texconfig localsetup. Trying to proceed anyway...\n";
	    exit( 1);
	}
    }

    # Check if fmtutil is recent enough, if not install a new one
    ipkgsystem( "${fmtutilcmd} --help </dev/null 2>&1 | grep listcfg >/dev/null");
    if (($? >> 8) != 0) {
	$dorepairownership = 1;
	print "### ${PROGNAME}: This TeX does not have a recent fmtutil. Installing one...\n";
	$fmtutilloc = `which fmtutil`;
	chomp( $fmtutilloc);
	ipkgsystem( "cp \"${II2PKGDIR}/fmtutil.${tlversion}\" \"$fmtutilloc\"") == 0
	    or die "### ${PROGNAME}: failed to install new fmtutil. Bailing out...\n";
    }

    checkFmtutilCfg();

    # Check is updmap is recent enough
    # TODO install a new one if too old
    ipkgsystem( "updmap --help </dev/null 2>&1 | grep listmaps >/dev/null");
    if (($? >> 8) != 0) {
	warn "### ${PROGNAME}: This TeX does not have a recent updmap. Bailing out...\n";
	exit( 1);
    }

    checkPersonalConfigs();
}

sub checkFmtutilCfg
{
    $fmtutilloc = `${kpsewhichcmd} --format='web2c files' fmtutil.cnf`;
    chomp( $fmtutilloc);
    ipkgsystem( "egrep '^[[:alnum:]]+[[:space:]]+mfw?[[:space:]]' \"$fmtutilloc\" >&2");
    if (($? >> 8) == 0) {
	$overwritefmtutil = 1;
	$dorepairownership = 1;
	warn "### ${PROGNAME}: fmtutil.cnf is not X11-safe.\n";
    }
    ipkgsystem( "egrep '^latex[[:space:]]+tex[[:space:]]' \"$fmtutilloc\" >&2");
    if (($? >> 8) == 0) {
	$overwritefmtutil = 1;
	$dorepairownership = 1;
	warn "### ${PROGNAME}: fmtutil.cnf contains non-ETeX LaTeX.\n" if $tlversion eq "tl2003";
    }
    ipkgsystem( "egrep '^pdflatex[[:space:]]+pdftex[[:space:]]' \"$fmtutilloc\" >&2");
    if (($? >> 8) == 0) {
	$overwritefmtutil = 1;
	$dorepairownership = 1;
	warn "### ${PROGNAME}: fmtutil.cnf contains non-PDFETeX PDFLaTeX.\n";
    }

    ipkgsystem( "egrep '^texinfo[[:space:]]+tex[[:space:]]+-[[:space:]]+-translate-file' \"$fmtutilloc\" >&2");
    if (($? >> 8) == 0) {
	$fmtutilcnf = 'tl2004';
	warn "### ${PROGNAME}: fmtutil.cnf contains TL2004 structure.\n";
    }
    else {
	$fmtutilcnf = 'tl2003';
	warn "### ${PROGNAME}: fmtutil.cnf does not contain TL2004 structure.\n";
    }
    $overwritefmtutil = $fmtutilcnf ne $tlversion if (not $overwritefmtutil);

    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? Only keep them 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 an 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 cont-en </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable ConTeXt EN\n";
	ipkgsystem( "${fmtutilcmd} --enablefmt cont-nl </dev/null") == 0
	    or warn "### ${PROGNAME}: failed to enable ConTeXt NL\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";
	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+)/) {
			$displayString .= "-$1|";
			$patternfile = $2;
			if ($patternfile eq 'language.dat') {
			    $langformats .= "$1, ";
			}
			$inactiveformats{$1} = 1;
			next;
		    }
		    if ($fmtitem =~ /\s*(\S+)\s+\S+\s+(\S+)/) {
			$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', 'cont-en', 'cont-nl')) {
	    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 latex\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";
	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{'american'} = 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: $langitem";
			$outcommented = ( $1 eq '%!' );
			if ($lastlang ne '') {
			    if ($outcommented) {
				# Make active
				$langitem =~ s/^\s*%!\s*//;
			    }
			}
			else {
			    if (not $outcommented) {
				# Make alias inactive because source is also
				$langitem = "%! " . $langitem;
			    }
			}
		    }
		    elsif ($langitem =~ /^\s*(%!)?\s*(\S+)\s+(\S+)/) { # Entry
			# warn "Entry: $langitem";
			$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 ((not $outcommented or
			     exists $defaultlanguages{$2}) and
			    $hyphefilefound ne '') {
			    $lastlang = $2;
			    if ($outcommented) {
				# Make active
				$langitem =~ s/^\s*%!\s*//;
			    }
			}
			else {
			    $lastlang = '';
			    if (not $outcommented) {
				# Make inactive
				$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.\n\nNote: the \\\"english\\\" alias is set to \\\"british\\\" if \\\"british\\\" is activated and \\\"american\\\" otherwise. Use \\\"american\\\" and \\\"british\\\" in your TeX file to be certain which language is used." -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;
	}
	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\" \"$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}\"/share/texmf.local/web2c/*.fmt");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/share/texmf.local/web2c/*.?fmt");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/share/texmf.local/web2c/*.oft");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/share/texmf.local/web2c/*.mem");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/share/texmf.local/web2c/*.log");
    ipkgsystem( "rm -f \"${II2INSTALLDIR}\"/share/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");
    ipkgsystem( "texlinks --silent </dev/null");
    if ($tlversion =~ /tl2003/) {
	`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t SetConfiguredSelectorSets -P "tl2003-bin-powerpc|tetex2-texmfe"`;
    }
    else {
	`"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t SetConfiguredSelectorSets -P "tl2004-bin-${arch}|tl2005-bin-${arch}|tetex3-texmfe"`;
    }
}

sub updateFontMappings
{
    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;
#    if (ipkgsystem( 'updmap --help 2>&1 </dev/null | grep "listavailablemaps" >/dev/null 2>&1') == 0) {
#	$updmaplistcmd = '--listavailablemaps';
#    }
#    else {
	$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"};
	    print "### ${PROGNAME}: Setting ownership of TeX installation in ${II2INSTALLDIR} to $realname ($uname). Please wait...\n";
	    ipkgsystem( "/usr/sbin/chown -R \"${uname}:admin\" ${II2INSTALLDIR}") == 0
		or die "### ${PROGNAME}: failed to run chown. 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 tex4htConfig
{
    if (not -x "${II2INSTALLDIR}/bin/${arch}-apple-darwin-current/mk4ht") {
	warn "### ${PROGNAME}: A mk4ht script is missing from your programs. My version will be installed.\n";
	ipkgsystem( "/bin/cp \"${II2PKGDIR}/mk4ht\" \"${II2INSTALLDIR}/bin/${arch}-apple-darwin-current/mk4ht\"") == 0
	    or die "### ${PROGNAME}: failed to install mk4ht script. Bailing out...\n";
    }

    if (not ipkgsystem( "/usr/bin/diff --ignore-all-space \"${II2PKGDIR}/mk4ht\" \"${II2INSTALLDIR}\"/bin/${arch}-apple-darwin-current/mk4ht >/dev/null 2>&1")) {
	warn "### ${PROGNAME}: Your mk4ht script differs from the one I carry as a possible update. I cannot detect which one is newer, but if you have problems you can try to remove ${II2INSTALLDIR}/bin/${arch}-apple-darwin-current/mk4ht and re-run this configuration script. My version will then be installed.\n";
    }

    print "### ${PROGNAME}: Installing special tex4ht.env.\n";
    $TEXMFMAIN=`kpsewhich -expand-var=\'\$TEXMFMAIN\'`; chomp( $TEXMFMAIN);
    $TEXMFTE=`kpsewhich -expand-var=\'\$TEXMFTE\'`; chomp( $TEXMFTE);
    $TEXMFLOCAL=`kpsewhich -expand-var=\'\$TEXMFLOCAL\'`; chomp( $TEXMFLOCAL);
    if (${TEXMFTE} ne '') {
	$TEXMFDIR=$TEXMFTE;
    }
    else {
	$TEXMFDIR=$TEXMFMAIN;
    }
    open( ENVIN, "<${II2PKGDIR}/tex4ht.env.in") or
	die "### ${PROGNAME}: I cannot read tex4ht.env.in. Bailing out...\n";
    @envin = <ENVIN>;
    close( ENVIN);
    # Hard coded fix, to be repaired:
    open( ENVOUT, ">${II2INSTALLDIR}/share/texmf.local/tex4ht/base/tex4ht.env") or
    open( ENVOUT, ">${II2INSTALLDIR}/share/texmf.gwtex/tex4ht/base/tex4ht.env") or
    open( ENVOUT, ">${II2INSTALLDIR}/share/texmf.tetex/tex4ht/base/tex4ht.env") or
    open( ENVOUT, ">${II2INSTALLDIR}/share/texmf/tex4ht/base/tex4ht.env") or
	die "### ${PROGNAME}: I cannot write tex4ht.env. Bailing out...\n";
    foreach my $line (@envin) {
	$line =~ s/%II2INSTALLDIR%/${II2INSTALLDIR}\/share\/texmf.local/g;
	$line =~ s/%TEXMFDIR%/${TEXMFDIR}/g;
	print ENVOUT $line;
    }
    close( ENVOUT);
    `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t SetConfiguredSelectorSets -P "tex4ht"`;
}

sub lmConfig
{
    print "### ${PROGNAME}: Preparing TeX for Latin Modern configuration...\n";
    ipkgsystem( "texhash \"$II2INSTALLDIR\"/share/texmf.local");
    if (ipkgsystem( "${kpsewhichcmd} cork-lm.map") == 0) {
	print "### ${PROGNAME}: Pre TL2005 style Latin Modern map names found...\n";
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map cork-lm.map </dev/null");
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map lm.map </dev/null");
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map qx-lm.map </dev/null");
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map texnansi-lm.map </dev/null");
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map ts1-lm.map </dev/null");
    }
    else {
	print "### ${PROGNAME}: TL2005 style Latin Modern map names found...\n";
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map lm-ec.map </dev/null");
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map lm-qx.map </dev/null");
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map lm-texnansi.map </dev/null");
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map lm-ts1.map </dev/null");
	ipkgsystem( "${updmapcmd} " . "--nohash --nomkmap --enable Map lm-t5.map </dev/null");
    }
    $dorunupdmap = 1;
    `"${II2RESOURCES}/doalerter" -s "${II2DOSERVER}" -V -t SetConfiguredSelectorSets -P "gwtex2"`;
}

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}/share/texmf.gwtex/fonts/truetype/gtamacfonts/${texname}") {
	    print "### ${PROGNAME}: running Fondu on \"${macfontfile}\".\n";
	    ipkgsystem( "/bin/mkdir -p \"${II2INSTALLDIR}/share/texmf.gwtex/fonts/truetype/gtamacfonts/${texname}\" && " .
			"cd \"${II2INSTALLDIR}/share/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}/share/texmf.gwtex/fonts/afm/gtamacfonts/${texname}") {
	    print "### ${PROGNAME}: running FontForge on \"${macfontfile}\".\n";
	    ipkgsystem( "/bin/mkdir -p \"${II2INSTALLDIR}/share/texmf.gwtex/fonts/afm/gtamacfonts/${texname}\" && " .
			"cd \"${II2INSTALLDIR}/share/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}/share/texmf.gwtex\", please wait...\n";
	ipkgsystem( "mktexlsr \"${II2INSTALLDIR}\"/share/texmf.gwtex") == 0
	    or warn "### ${PROGNAME}: failed to run mktexlsr on texmf.gwtex.\n";
    }
}

sub lmFontConversion
{
    print "### ${PROGNAME}: Latin Modern fonts will be converted for GUI use.\n";
    my $macfontdir = "/Library/Fonts/Latin Modern";

    my $lmpfbdir = `${kpsewhichcmd} lmr10.pfb`;
    chomp( $lmpfbdir);
    $lmpfbdir =~ s/\/lmr10.pfb$//;
    if ($lmpfbdir eq '') {
	warn "### ${PROGNAME}: This script needs the Latin Modern fonts but it cannot find them. Stopping conversion.\n";
    }
    else {
	print "### ${PROGNAME}: Latin Modern fonts found in $lmpfbdir\n";
    }

    if (not -x "/usr/local/bin/fontforge") {
	print "### ${PROGNAME}: This script needs fontforge to be available in /usr/local/bin. Stopping conversion.\n";
	return;
    }
    else {
	print "### ${PROGNAME}: FontForge found.\n";
    }
    if (not -x "${II2PKGDIR}/lmcreatefamilies.pe") {
	warn "### ${PROGNAME}: This script needs lmcreatefamilies.pe to be available in the package. Conversion stopped.\n";
	return;
    }
    if (not -x "${II2PKGDIR}/convert.pe") {
	warn "### ${PROGNAME}: This script needs convert.pe to be available in the package. Conversion stopped.\n";
	return;
    }
    $versionstr = `/usr/local/bin/fontforge --version`;
    chomp( $versionstr);

    $versionstr =~ /.*(pfaedit|fontforge) (2\d)?(\d\d)(\d\d)(\d\d)$/;

    if ($2 ne '') {
	$year = "$2$3";
    }
    else {
	if ($2 =~ /^9/) {
	    $year = "19$2";
	}
	else {
	    $year = "20$2";
	}
    }
    # warn "$year $4 $5";
    my $notok = (($year lt "2004")
		 or (($year eq "2004") and (($3 lt '05') and ($4 lt '19')))
		 );
    if ($notok) {
	warn "### ${PROGNAME}: This script needs fontforge version 20040519 or higher in /usr/local/bin. Stopping conversion.\n";
	return;
    }
    else {
	print "### ${PROGNAME}: FontForge has the right version.\n";
    }

    ipkgsystem( "/bin/rm -rf \"$macfontdir\"");
    ipkgsystem( "/bin/mkdir -p \"$macfontdir\"");
    if (not -w $macfontdir) {
	warn "### ${PROGNAME}: This script needs write access in \"$macfontdir\". Stopping conversion.\n";
	return;
    }
    print "### ${PROGNAME}: Converting Latin Modern Type 1 fonts to fonts in \"/Library/Fonts/Latin Modern\" for use in GUI apps. Please wait...\n";
    ipkgsystem( "\"${II2PKGDIR}/\"lmcreatefamilies.pe \"${lmpfbdir}\" \"${macfontdir}\"") == 0
	or warn "### ${PROGNAME}: failed to run FontForge conversion script.\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}\"");
	}
    }
}

sub setConfigUser
{
    if (-e "${II2INSTALLDIR}/bin/${arch}-apple-darwin-current/texconfig-sys") {
	if ($> == 0) {
	    print "### ${PROGNAME}: System wide configuration, TL2005-style.\n";
	    ${configforuser} = 'root';
	    ${sudocmd} = "sudo -H -u ${configforuser}";
	    ${texconfigcmd} = "${sudocmd} texconfig-sys";
	    ${fmtutilcmd} = "${sudocmd} fmtutil-sys";
	    ${updmapcmd} = "${sudocmd} updmap-sys";
	    ${kpsewhichcmd} = "${sudocmd} kpsewhich";
	}
	else {
	    print "### ${PROGNAME}: Configuring system-wide for user $ENV{'II2USER'}, TL2005-style.\n";
	    ${configforuser} = $ENV{'II2USER'};
	    ${sudocmd} = "";
	    ${texconfigcmd} = "${sudocmd} texconfig-sys";
	    ${fmtutilcmd} = "${sudocmd} fmtutil-sys";
	    ${updmapcmd} = "${sudocmd} updmap-sys";
	    ${kpsewhichcmd} = "${sudocmd} kpsewhich";
	}
    }
    else {
	if ($> == 0) {
	    print "### ${PROGNAME}: System wide configuration, pre-TL2005-style.\n";
	    ${configforuser} = 'root';
	    ${sudocmd} = "sudo -H -u ${configforuser}";
	    ${texconfigcmd} = "${sudocmd} texconfig";
	    ${fmtutilcmd} = "${sudocmd} fmtutil";
	    ${updmapcmd} = "${sudocmd} updmap";
	    ${kpsewhichcmd} = "${sudocmd} kpsewhich";
	}
	else {
	    print "### ${PROGNAME}: Configuring system-wide for user $ENV{'II2USER'}, pre-TL2005-style.\n";
	    ${configforuser} = $ENV{'II2USER'};
	    ${sudocmd} = "";
	    ${texconfigcmd} = "${sudocmd} texconfig";
	    ${fmtutilcmd} = "${sudocmd} fmtutil";
	    ${updmapcmd} = "${sudocmd} updmap";
	    ${kpsewhichcmd} = "${sudocmd} kpsewhich";
	}
    }
}

# $Id: tex.configure 110 2006-12-28 21:58:00Z gctwnl $

