#!/usr/bin/perl
# webaccess.pl:  Restricts access to web pages.

foreach (@ARGV){			#set remove flag
  if (m/^-/){
      if (m/--remove|-R/) {$remove=1;}
      else {@usage;}
      next;
      }
   else {@argv= (@argv,$_);}
}
@ARGV=@argv;

sub usage{
print <<EOT;
Usage: 3 arguments:   webaccess.pl dir usrname passwd 
Where dir is the (relative path) directory that will have restricted access. 
Program writes/overwrites the files .htaccess .htgroup.cgi and .htpasswd.cgi
Usage: 1 argument and -R:   webaccess.pl -R dir
Removes all Web access files from dir. Allows for unrestricted browsing.
EOT
exit;
}

$dir=$ARGV[0];
$user=$ARGV[1];
$passwd=$ARGV[2];

use Cwd;					#Camel 386!  get pwd PWD
$path= cwd();

$encrpass= encrypt_it($passwd);

$htaccess= "$path/$dir/.htaccess";
$htpasswd= "$path/$dir/.htpasswd.cgi";
$htgroup= "$path/$dir/.htgroup.cgi";





####### MAIN STUFF STARTS HERE ########
if ($remove){
  $direct= "$path/$dir";
  if (!-e $direct){&nodir;}
  unlink($htaccess,$htpasswd,$htgroup) || &no_unlink;
  exit;
}

if (!$passwd) {&usage();}

# MAKES .htaccess
open(OUT, ">$htaccess") || die("Can't open file $htaccess for write: $!");

print OUT <<EOT;
AuthUserFile $htpasswd
AuthGroupFile $htgroup
AuthName restricted
AuthType Basic

<Limit GET POST>
Order Allow,Deny
Allow from all   
Require group users
</Limit>
EOT
close(OUT);
chmod(0664,$htaccess);


# MAKES .htpasswd.cgi
open(OUT, ">$htpasswd") || die("Can't open file $htpasswd for write: $!");
print OUT <<EOT;
$user:$encrpass
EOT

chmod(0664,$htpasswd);
 
# MAKES .htgroup.cgi
open(OUT, ">$htgroup") || die("Can't open file $htgroup for write: $!");
print OUT <<EOT;
users: $user
EOT
;
chmod(0664,$htgroup);
close(OUT);

############# END MAIN ##################3
 
# This provides two salt characters and encrypts the password
# usage: $enc = encrypt_it($passwd);
sub encrypt_it{
local($a1,$a2,$salt,$encrypted);
srand;
@alphnum= ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
push(@alphnum,("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"));
$a1= @alphnum[rand(61)];
$a2= @alphnum[rand(61)];
$salt = $a1 . $a2;	
$encrypted= crypt($_[0],$salt);
return($encrypted);
}

sub nodir{
print <<EOT;
Directory $dir doesn't exist.
EOT
}

sub no_unlink{
print "Couldn't remove files: $!\n";
}

__END__

$word = $ARGV[0];

srand;					#Sets randomizer

$encrypted = crypt($word,"$salt");	#Converts word into its encrypted form

print ("$encrypted\n");
