#!/usr/bin/perl
use Win32::TieRegistry(Delimiter => '/');
use Getopt::Std;

use bytes;

getopts('d:r');

$path = join(' ', @ARGV);

unless ($path)
{
    die <<'EOT';
    addpath [-r] [-d file] path
    
Adds the path to the system path or removes it (-r)

  -d file   debug output to file
  -r        removes path from system path
EOT
}

my ($regKey) = "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Control/Session Manager/Environment//Path";
open(DEBUG, ">$opt_d") if ($opt_d);

if (Win32::IsWinNT())
{
    if ($opt_r)
    { removepathnt($path); }
    else
    { addpathnt($path); }
}

sub addpathnt
{
    my ($path) = @_;
    my ($currPath) = $Registry->{$regKey};
    my ($out);
    
    $path = "\"$path\"" if ($path =~ m/\s/o);
    print DEBUG "adding $path to $currPath\n" . join(' ', unpack('C*', $currPath)) . "\n" if ($opt_d);
    $out = 1 if ($currPath =~ s/\000(.*)$//o);
    if ($currPath !~ m/(^|;)\Q$path\E(;|$)/oi)
    { 
        $currPath .= ";$path";
        $out = 1;
    }
    elsif (!defined $currPath)
    { 
        $currPath = $path;
        $out = 1;
    }
    $Registry->{$regKey} = $currPath if ($out);
    print DEBUG "Path is now $Registry->{$regKey}\n" if ($opt_d);
}


sub removepathnt
{
    my ($path) = @_;
    my ($currPath) = $Registry->{$regKey};
    
    $path = "\"$path\"" if ($path =~ m/\s/o);
    print DEBUG "removing $path from $currPath\n" if ($opt_d);
    if ($currPath =~ s/;\Q$path//oi || $currPath =~ s/\Q$path;//oi)
    { $Registry->{$regKey} = $currPath; }
    print DEBUG "path now $Registry->{$regKey}\n" if ($opt_d);
}
