#!/usr/local/bin/perl
# Troop344 Member Registration CGI
#

use CGI qw(:standard :html13);
use CGI::Carp qw(fatalsToBrowser);

################################################################
# Getting current date
################################################################
($mday, $mon, $year)=(localtime)[3, 4, 5];
$ThisYear = 1900 + $year;
$ThisMonth = $mon + 1;
$ThisDay = $mday;
$Today = sprintf("%02d/%02d/%04d", $ThisMonth, $ThisDay, $ThisYear);

$sendmail_command = "/usr/sbin/sendmail";

################################################################
# User information.
################################################################
#$login_id=$ENV{'REMOTE_USER'};

################################################################
### LOAD PASSWORD DATA FROM FILE 
################################################################
$members_file="/home/troop344/lib/WWW_members_only.passwd";
open (MEMBERS, $members_file) || die "Unable to open the members data file!";
@raw_records = (<MEMBERS>);
close(MEMBERS);
$TimeOfLastUpdate = localtime((stat($members_file))[9]);


#---- Disable Registration page ----
print "Content-type: text/html\n\n";
print <<EndOfRedirect;
<HTML>
<HEADER>
    <TITLE>Auto-Forward</TITLE>
    <meta http-equiv="refresh" content="0; url=http://www.bsa344-raleigh.org/home.html">
</HEADER>
<BODY BGCOLOR=BLACK 
      VLINK=BLUE>
</body>
</HTML>
EndOfRedirect

exit;

########################
### Extract the User IDs
########################
@unsorted = ();
foreach $line (@raw_records)
   {
   chomp $line;
   @field = split /:/, $line;
   @unsorted = (@unsorted, "$field[0]");
   }
$members = join /~/, (sort @unsorted);

############################
### This is the main process
############################

##########################################################
### If there are any parameters, then this is a submission
##########################################################
if(param())
   {
   $error = 0;
   $id_error = "";
   $pswd_error = "";
   $email_error = "";
   $name_error = "";

   ######################
   #### check the User ID
   ######################
   $sub_id = param('user_id');
   $sub_id =~ s/^ //g;
   $sub_id =~ s/ $//g;
   
   if ($members =~ /$sub_id/)
      {
      $error += 1;
      $id_error = "User ID Already Exists!";
      }
   elsif (!length $sub_id)
      {
      $error += 1;
      $id_error = "No User ID Specified!";
      }
   elsif ((length $sub_id) < 4)
      {
      $error += 1;
      $id_error = "User ID must be at least 4 characters";
      }
   elsif ($sub_id =~ /\s/)
      {
      $error += 1;
      $id_error = "User ID cannot contain any spaces";
      }
   elsif ($sub_id !~ /^[A-Za-z0-9_]+$/)
      {
      $error += 1;
      $id_error = "User ID can only contain letters, numbers and underscores";
      }

   ######################
   ### Check the password
   ######################
   $sub_pswd1 = param('pswd1');
   $sub_pswd1 =~ s/^ //g;
   $sub_pswd1 =~ s/ $//g;
   
   $sub_pswd2 = param('pswd2');
   $sub_pswd2 =~ s/^ //g;
   $sub_pswd2 =~ s/ $//g;
   
   if ((!length $sub_pswd1) && (!length $sub_pswd2))
      {
      $error +=1;
      $pswd_error = "No Password Specified!";
      }
   elsif ($sub_pswd1 =~ /\s/)
      {
      $error += 1;
      $id_error = "Password cannot contain any spaces";
      }
   elsif ($sub_pswd1 !~ /^[A-Za-z0-9_]+$/)
      {
      $error += 1;
      $id_error = "Password can only contain letters, numbers and underscores";
      }
   elsif ((length $sub_pswd1) < 4)
      {
      $error += 1;
      $pswd_error = "Password must be at least 4 characters";
      }
   elsif ($sub_pswd1 ne $sub_pswd2)
      {
      $error += 1;
      $pswd_error = "Password Entries do not Match!";
      }

   ##################
   ### Check the name
   ##################
   $sub_name = param('name');
   $sub_name =~ s/^ //g;
   $sub_name =~ s/ $//g;

   if (!length $sub_name)
      {
      $error += 1;
      $name_error = "A name must be specified";
      }

   ###########################
   ### Check the Email address
   ###########################
   $sub_email = param('email');
   $sub_email1 = $sub_email;
   $sub_email =~ s/^ //g;
   $sub_email2 = $sub_email;
   $sub_email =~ s/ $//g;

   if (!length $sub_email)
      {
      $error += 1;
      $name_error = "An E-mail address must be specified";
      }
   elsif ($sub_email !~ /@/)
      {
      $error += 1;
      $email_error = "Must specify a valid E-mail Address";
      }
   
   #######################################################################
   ### If no errors, generate the encrypted password and submit via E-mail
   #######################################################################
   if (!$error)
      {
#      @args = { "htpasswd", "-b", "-c", "/users/troop344/lib/request.temp", "$sub_id", "$sub_pswd1" };
#      system @args == 0 
#        or die "Unable to generate password and submit!\n";

      ####################################
      ### Calculate a random value of SALT
      ####################################
      @chars = split //, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
      $salt = pack("aa", $chars[int(rand (scalar @chars))], $chars[int(rand (scalar @chars))]);

      ########################
      ### Encrypt the password
      ########################
      $paswd = crypt($sub_pswd1, $salt);
      
      ###########################
      ### Send the E-mail request
      ###########################
      open(MAIL,"| $sendmail_command -t");
      print MAIL <<EndOfMail;
To: Webmaster\@BSA344-Raleigh.org
From: $sub_name <$sub_email>
Subject: Member Area Web Access Request
Bcc: bmarks\@cisco.com

$sub_id:$paswd\n
EndOfMail
      close(MAIL);
      
      #############################################
      ### Append record to file of requesting users
      #############################################
      $request="/home/troop344/lib/request.txt";
      open (REQUEST, ">>$request") || die "Unable to open the request data file!";
      print REQUEST "$sub_name~$sub_email~$sub_id:$paswd\n";
      close(REQUEST);

      ########################
      ### Display confirmation
      ########################
      Output_Header();
      Output_Confirmation();
      Output_Footer();
      }
   else
      {
      Output_Header();
      Output_Form();
      print "<hr>";
      print "<small>";
      print "The following errors were detected.  Please correct and resubmit.<br><br>";
      if (length $id_error)
         {
         print "$id_error<br>";
         }
      if (length $pswd_error)
         {
         print "$pswd_error<br>";
         }
      if (length $name_error)
         {
         print "$name_error<br>";
         }
      if (length $email_error)
         {
         print "$email_error<br>";
         }
      print "</small>\n";
      Output_Footer();
      }

   }
##########################################################
### If no parameters, then this is an initial form display
##########################################################
else
   {
   Output_Header();
   Output_Form();
   Output_Footer();
   }


###########################################################
###########################################################
###                                                     ###
### End of Mainline Code - All SubRoutines Below Here   ###
###                                                     ###
###########################################################
###########################################################

#################################
### Routine to diplay Page Header
#################################
sub Output_Header
   {
   print "Content-type: text/html\n\n";
   print <<EndOfHeader;
   <HTML>
   <HEADER>
     <TITLE>Troop 344 Member Registration</TITLE>
     <script language="JavaScript1.1" src="js-source/default.js">
     </script>
   </HEADER>
   <BODY BGCOLOR=BLACK VLINK=BLUE>
   <table border=0 width=640 background=\"gifs/watermark.gif\">
     <tr>
       <td align=left valign=top>
         <NOBR>
           <IMG SRC=\"gifs/bsalogo.gif\" BORDER=0 HEIGHT=200 WIDTH=170
           ><IMG SRC=\"gifs/stmarks.gif\" BORDER=0 HEIGHT=200 WIDTH=300
           ><IMG SRC=\"gifs/character.gif\" BORDER=0 HEIGHT=200 WIDTH=170>
         </NOBR>
         <hr width=640 align=left>
         <!-------------------------->
         <!--  Navigation Buttons  -->
         <!-------------------------->
         <table border=0 width=100%>
           <tr VALIGN=top>
             <td ALIGN=center WIDTH=95>
               <a href="home.html"
                  onMouseOver="imageOn(3); return(true)"
                  onMouseOut="imageOff(3); return(true)">
                 <IMG SRC="gifs/home_std.gif" BORDER=0 HEIGHT=28 WIDTH=91></a>
               <a href="gallery"
                  onMouseOver="imageOn(4); return(true)"
                  onMouseOut="imageOff(4); return(true)">
                 <IMG SRC="gifs/photos_std.gif" BORDER=0 HEIGHT=28 WIDTH=91></a>
               <a href="http://picasaweb.google.com/Troop344Raleigh"
                  onMouseOver="imageOn(5); return(true)"
                  onMouseOut="imageOff(5); return(true)">
                 <IMG SRC="$dir/gifs/photos_std.gif" BORDER=0 HEIGHT=28 WIDTH=91></a>
               <a href="location.html"
                  onMouseOver="imageOn(6); return(true)"
                  onMouseOut="imageOff(6); return(true)">
                 <IMG SRC="gifs/map_std.gif" BORDER=0 HEIGHT=28 WIDTH=91></A>
               <a href="calendar.html" TARGET=calendar
                  onMouseOver="imageOn(7); return(true)"
                  onMouseOut="imageOff(7); return(true)">
                 <IMG SRC="gifs/schedule_std.gif" BORDER=0 HEIGHT=28 WIDTH=91></a>
               <A HREF="eagles.html"
                  onMouseOver="imageOn(8); return(true)"
                  onMouseOut="imageOff(8); return(true)">
                 <IMG SRC="gifs/eagles_std.gif" BORDER=0 HEIGHT=28 WIDTH=91></A>
               <A HREF="projects.html"
                  onMouseOver="imageOn(9); return(true)"
                  onMouseOut="imageOff(9); return(true)">
                 <IMG SRC="gifs/projects_std.gif" BORDER=0 HEIGHT=28 WIDTH=91></A>
               <A HREF="contacts.html"
                  onMouseOver="imageOn(10); return(true)"
                  onMouseOut="imageOff(10); return(true)">
                 <IMG SRC="gifs/contacts_std.gif" BORDER=0 HEIGHT=28 WIDTH=91></A>
               <A HREF="documents.html"
                  onMouseOver="imageOn(11); return(true)"
                  onMouseOut="imageOff(11); return(true)">
                 <IMG SRC=gifs/documents_std.gif" BORDER=0 HEIGHT=28 WIDTH=91></A>
               <A HREF="members_only/index.html"
                  onMouseOver="imageOn(12); return(true)"
                  onMouseOut="imageOff(12); return(true)">
                 <IMG SRC="gifs/members_std.gif" BORDER=0 HEIGHT=28 WIDTH=91></A>
               <IMG SRC="gifs/register_sel.gif" BORDER=0 HEIGHT=28 WIDTH=91>
             </td>
             <td>
EndOfHeader
   }

#####################################
### Routine to output the Page Footer
#####################################
sub Output_Footer
   {
   print <<EndOfFooter;
             </TD>
           </tr>
         </table>
        <!----------------------------------------->
        <!--  Page ownership and update display  -->
        <!----------------------------------------->
         <hr width=640 align=left>
         <small>This page owned by <a href=mailto:Webmaster\@BSA344-Raleigh.org>Troop 344 WebAdmin</a><br>
         <small><i>Last updated on $TimeOfLastUpdate</i></small><br>
         </small><br>
       </td>
     </tr>
   </table>
   </BODY>\n
   </HTML>\n
EndOfFooter
   }


############################
### Subroutine to print form
############################
sub Output_Form
   {
   print start_form();
   ###########################################
   # First Table with reset and submit buttons
   ###########################################
   print table({-border=>"0", -cellpadding=>"3", -width=>"100%"},
               Tr(
                  td({-colspan=>"2",-align=>"center"},font({-size=>"3"},b("Request Access to Member-only Area"))),
                 ),

               ################
               ##### Full Name
               ################
               Tr({-valign=>"top"},
                  td({-align=>"right"},font({-size=>"2"},b("Full Name"))),
                  td({-align=>"left"}, font({-size=>"3"},textfield("name", "", 50))),
                 ),

               ####################
               ##### E-Mail Address
               ####################
               Tr({-valign=>"top"},
                  td({-align=>"right"},font({-size=>"2"},b("E-Mail Address"))),
                  td({-align=>"left"}, font({-size=>"3"},textfield("email", "", 50))),
                 ),

               ###########
               ### User ID
               ###########
               Tr({-valign=>"top"},
                  td({-align=>"right"},font({-size=>"2"},b("User ID"))),
                  td({-align=>"left"},font({-size=>"3"},textfield("user_id", "", 15))),
                 ),

               ############
               ### Password
               ############
               Tr({-valign=>"top"},
                  td({-align=>"right"},font({-size=>"2"},b("Password"))),
                  td({-align=>"left"},font({-size=>"3"},password_field("pswd1", "", 15))),
                 ),

               ###########################
               ### Password - Verification
               ###########################
               Tr({-valign=>"top"},
                  td({-align=>"right"},font({-size=>"2"},b("Verify Password"))),
                  td({-align=>"left"},font({-size=>"3"},password_field("pswd2", "", 15))),
                 ),

               ###########
               ### Buttons
               ###########
               Tr(
                  td({-align=>"left"},defaults("Reset")),
                  td({-align=>"right"},submit("Submit")),
                 ),

               );
   
   print end_form();
   }

####################################
### Subroutine to print confirmation
####################################
sub Output_Confirmation
   {
   print start_form();
   print table({-border=>0, -width=>"100%"},
                 Tr(
                    td({-align=>"left"},font({-size=>"5"},b("Request has been Processed")),"<br>",
                       font({-size=>"2"},"Please allow 24 hours for your User ID to become active")),
                    td({-align=>"right"},defaults("Enter Another Request")),
                   )
              );
   print end_form();
   }


