#  SetPerl.pl
#  Example 1.2:
#  ----------------------------------------
#  From "Win32 Perl Scripting: Administrators Handbook" by Dave Roth
#  Published by New Riders Publishing.
#  ISBN # 1-57870-215-1
#
#  This script is used to configure a machine to use Perl. It works
#  by modifying various environmental variables (such as the PATH)
#  and registering file extensions with the Perl executable.
#
print "From the book 'Win32 Perl Scripting: The Administrator's Handbook' by Dave Roth\n\n";

$TIMEOUT = 30;
$PERL_DIR = 'c:\perl';
$PERL_EXTENSION = '.pl';

# Check that the path is accurate
if( -d $PERL_DIR )
{
    if( ! -f "$PERL_DIR\\bin\\perl.exe" )
    {
        print "WARNING: You are missing your Perl executable.\n";
    }
}
else
{
    print "WARNING: You are missing your Perl directory.\n";
}

# Before anything, set the file extension association
print "Associating $PERL_EXTENSION to perl...";
`assoc $PERL_EXTENSION=PerlScript`;
print "done\n";

# Now link the association with Perl
print "Linking the perl extension to perl executable...";
$Command ='%PERL%\bin\perl.exe "%1" %*';
`ftype PerlScript=$Command`;
print "done.\n";

# Set the Perl variable
print "Setting Perl environment variable...";
if( $Result = ModifyVar( 'Perl', $PERL_DIR ) )
{
    print ( ( 0 < $Result )? "successful\n":"wrote over previous value\n" );
}
else
{
    print "failure\n";
}

# Add Perl to the system path...
print "Setting path...";
if( $Result = ModifyPath( 'Path', '%PERL%\bin' ) )
{
    print ( ( 0 < $Result )? "successful\n":"already set\n" );
}
else
{
    print "failure\n";
}

# Add .pl to the path extension list
print "Setting path extensions...";
if( $Result = ModifyPath( 'PATHEXT', $PERL_EXTENSION ) )
{
    print ( ( 0 < $Result )? "successful\n":"already set\n" );
}
else
{
    print "failure\n";
}

sub ModifyVar
{
    my( $VarName, $VarValue ) = @_;
    my $PrevValue = Win32::AdminMisc::GetEnvVar( $VarName, ENV_SYSTEM );
    my $Result = Win32::AdminMisc::SetEnvVar( $VarName, $VarValue, ENV_SYSTEM, $TIMEOUT );
    $Result *= -1 if( defined $PrevValue );
    return( $Result );
}

sub ModifyPath
{
    my( $VarName, $VarValue ) = @_;
    my $Result = -1;
    my $Path = Win32::AdminMisc::GetEnvVar( $VarName, ENV_SYSTEM );
    if( defined $Path )
    {
        my $RegexValue = $VarValue;
        $RegexValue =~ s/([.$%@()\[\]\\\/])/\\$1/g;
        if( $Path !~ /$RegexValue/i )
        {
            $Path .= ";$VarValue";
            $Path =~ s/;+/;/g;
            $Result = Win32::AdminMisc::SetEnvVar( $VarName, $Path, ENV_SYSTEM, $TIMEOUT );
        }
    }
    else
    {
        $Result = 0;
    }
    return( $Result );
}


