#!/usr/bin/perl

$ENV{PATH} = "/usr/bin:/bin:/usr/sbin:/sbin";

my $scriptdirname = $0;
my $manpathline = $ARGV[0];
my $protectarg = $ARGV[1];
my $removearg = $ARGV[2];

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

$protectstring = (defined( $protectarg) ? $protectarg : "setmanpath");
$removeonly = $removearg =~ /^remove$/;

($scriptdirname) = $scriptdirname =~ /([A-Za-z\._\-\/ ]+)/;
$scriptdirname=`/usr/bin/dirname $scriptdirname`;
chomp( $scriptdirname);
if ($scriptdirname ne "") {
    chdir( "$scriptdirname") or die "Cannot chdir to $scriptdirname\n";
}
else {
    warn "Empty scriptdirname \"$scriptdirname\"\n";
}

$exitval = 0;

&adapt_manpath( "/etc/manpath.config", $manpathline, $protectstring, $removeonly);		# 10.3
&adapt_manpath( "/usr/share/misc/man.conf", $manpathline, $protectstring, $removeonly);	# 10.4 and up

if ($exitval) {
    warn "There were $exitval errors. Please read the warning messages,\n";
}

exit $exitval;

sub adapt_manpath {
    my $manpath_cfg_file = shift;
    my $manpath_line = shift;
    my $protectstring = shift;
    my $removeonly = shift;

    if (open MANPATH, "<$manpath_cfg_file") {
	@manpathfile = <MANPATH>;
	close MANPATH;

	# Fix line such that it corresponds with the syntax of the file we are
	# changing.
	my $oldmanpathconf = grep( /(MANDATORY|OPTIONAL)_MANPATH/, @manpathfile);
	if ($oldmanpathconf > 0) {
	    warn "Old style $manpath_cfg_file.\n";
	    $manpath_line =~ s/^MANPATH\s/MANDATORY_MANPATH /;
	}
	else {
	    warn "New style $manpath_cfg_file.\n";
	    $manpath_line =~ s/^(OPTIONAL|MANDATORY)_MANPATH\s/MANPATH /;
	}

	my $manadditionfound;
	if (open MANPATH, ">$manpath_cfg_file") {
	    foreach $line (@manpathfile) {
		if ($line =~ /^## $protectstring modifications end at/) {
		    $manadditionfound = 0;
		    next;
		}
		next if ($manadditionfound);
		if ($line =~ /^## $protectstring modifications start/) {
		    $manadditionfound = 1;
		    next;
		}
		print MANPATH $line;
	    }
	    close MANPATH;

	    if (not $removeonly) {
		$date = `date`;
		print "$0: Applying $protectstring man path addition of $texmandirto $manpath_cfg_file (Works on Mac OS X 10.2 and higher)\n";
		open MANPATHCONFIG, ">>$manpath_cfg_file" or die "Cannot append manpath.config file";
		print MANPATHCONFIG "## $protectstring modifications start at $date## Do not remove previous line\n";
		print MANPATHCONFIG "$manpath_line\n";
		print MANPATHCONFIG "## Do not remove next line\n## $protectstring modifications end at $date";
		close MANPATHCONFIG;
		print "Man path in $manpath_cfg_file set.\n";
	    }
	}
	else {
	    warn "You do not have write permissions on $manpath_cfg_file. Man path not set. Run with administrator access.\n";
	    $exitval++;
	}
    }
    else {
	print "Cannot read $manpath_cfg_file file. You are probably not running Mac OS X 10.3. Man path not set. Don't worry. I Will try different layouts/versions.\n";
    }
}

# $Id: settexpath 42 2005-12-28 22:57:55Z gctwnl $
