#!/usr/bin/perl
# install or repair ~/.MacOSX/environment.plist
#  2003 Ronald Florence

my $home = `cd ~/; pwd`;
chop $home;
my @path = ("/usr/bin", "/bin", "/sw/bin", "/usr/local/bin", "/usr/local/teTeX/bin/powerpc-apple-darwin-current");

# see if they have an environment.plist
if (open F, "+<$home/.MacOSX/environment.plist")
{
    my @file = <F> ;
# create a backup
    open FO, ">$home/.MacOSX/environement.plist-orig";
    print FO @file;
    close FO;
    my $i ;
    for ($i = 0; $i < @file; $i += 1)
    {  last if $file[$i] =~ /<key>PATH<\/key>/ ; }
# if they don't have PATH defined we insert it
    if ($i == @file)
    {  
       splice @file, -2, 0, "\t<key>PATH</key>\n", "\t<string>".join(":",@path)."</string>\n";
    }
    else
# we put any path elements that are not in our path 
# after /usr/bin, and /bin, but before the local paths
    {  my $str = $file[$i + 1] ;
       die "Format error!\n" unless $str =~ /<string>(.*)<\/string>$/ ;
       my @dirs = split(':', $1) ;
       for my $element (@dirs)
       { splice @path, -3, 0, $element unless grep $_ eq $element, @path; }
       $file[$i+1] = "\t<string>".join(":",@path)."</string>\n";
    }
    seek F, 0, 0 ;
    print F @file ;
    close F ;
} 
else 
# they don't have an environment.plist, and probably don't have 
# the directory either, so we create both
{
    opendir(MACOSX, "$home/.MacOSX") || mkdir ("$home/.MacOSX", 0755);
    open(F, ">$home/.MacOSX/environment.plist") || die "cannot open $!\n";
    print F <<EOF;
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
	<key>PATH</key>
EOF
    print F "\t<string>".join(":",@path)."</string>\n", 
            "</dict>\n", 
            "</plist>\n";
    closedir(MACOSX);
    close F;
}
