#!/usr/bin/perl
# req-quote.cgi - handles online service requests

$0="foof.cgi";
$next="foof2.cgi";

# host, urlpath, auth or subroutine, extra info regex, speeds, postdata, 
# hash of regexs by service, hash of substitutions, hash of adsl up speeds
%PROVIDER=(
           'Northpoint' => ['', '', \&npGet,
                            '',
#                            'WIRE DIST ([0-9.]+) (WIRE DIST)',
                            [ 144, 160, 200, 416, 784, 1040, 1544 ],
                            '',
                            {'Business' => '',
#                            {'Business' => 'MAX SPEED ([0-9.]+) (MAX SPEED)',
                             'Residential' => '',
                            },
                            {'MAX SPEED' => 'SDSL',
                             'WIRE DIST' => 'Wire Distance',
                            },
                            {},
                            ],
           'Megapop' => ['dsl.megapop.net', '/servlets/qualify2', 
                         'NTQwMjpmdG00NTc=', '', '',
                         'npa=%s&nxx=%s&lastfour=%s&street1=%s&city=%s&state=%s&zip=%s&targeturl=http://xapi.covad.com/servlet/MainVCAServlet', 
                         {'Business' => 'name=svc[0-9]+ value="([0-9.]+)-(.DSL)',
                          'Residential' => 'name=svc[0-9]+ value="([0-9.]+)-(Consumer)"',
                         },
                         { 'Consumer' => 'ADSL' },
                         {'384' => '128', '768' => '384', '1500' => '384'},
                        ],
);
%PRICE=('Business' => {},
        'Residential' => { 'ADSL 384/128' => 49.95,
                           'ADSL 768/384' => 79.95,
                         }
);

# This line prepares the server to parse HTML style output
print "Content-type: text/html\n\n";
print "<BODY bgcolor=\"#ffffff\" text=\"#222222\">";
print join('',`cat $ENV{'DOCUMENT_ROOT'}/stdhdr.html`)."<P>";

# Get input from the form

if($ENV{'REQUEST_METHOD'} eq 'POST') {
  read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
} else {
  $buffer=$ENV{'QUERY_STRING'};
}
$buffer =~ s/\000//g;

# Split the buffer into name-value pairs

@pairs = split(/&/, $buffer);

foreach $pair (@pairs)
{
  ($name, $value) = split(/=/, $pair);
   $value =~ tr/+/ /;
   $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
   $FORM{$name} = $value;
}

if(scalar keys %FORM < 2) {
  print <<EOF;
<TITLE>Products &amp; Services | $FORM{Service} DSL - PreQual Service</TITLE>
<FORM action=$0 method=POST><TABLE BORDER=1>
<TR><TD>Phone</TD>
<TD>(<INPUT name=FRM_NPA SIZE=3 MAXLEN=3>) 
<INPUT name=FRM_NXX SIZE=3 MAXLEN=3> -
<INPUT name=FRM_XXXX SIZE=4 MAXLEN=4></TD></TR>
<TR><TD>Address</TD><TD><INPUT name=FRM_ADDR></TD></TR>
<TR><TD>City</TD><TD><INPUT name=FRM_CITY></TD></TR>
<TR><TD>State</TD><TD><INPUT name=FRM_STATE></TD></TR>
<TR><TD>zip</TD><TD><INPUT name=FRM_ZIP></TD></TR>
EOF
  print <<EOF if($FORM{'Service'} eq '');
<TR><TD COLSPAN=2 ALIGN=RIGHT>
<INPUT type=radio name=Service value="Business">Business
<INPUT type=radio name=Service value="Residential">Residential</TD></TR>
EOF
  print <<EOF;
<TR><TD COLSPAN=2 ALIGN=RIGHT><INPUT type=submit value=Submit></TD></TR>
</TABLE></FORM>
EOF
  print join('',`cat $ENV{'DOCUMENT_ROOT'}/stdftr.html`);
  print "</BODY>";
  exit;
}

# Check that required fields are filled in
foreach("FRM_ADDR", "FRM_CITY", "FRM_STATE", "FRM_ZIP",
        "FRM_NPA", "FRM_NXX", "FRM_XXXX") {
  &blank_response if($FORM{$_} eq '');
  $FRM{$_}=$FORM{$_};
  $FRM{$_}=~s/([^0-9A-Za-z])/sprintf("%%%02x",ord($1))/ge;
}
foreach("FRM_NPA", "FRM_NXX", "FRM_XXXX") {
  &blank_response if(length($FORM{$_}) != length($_)-4);
}

if(!exists($PRICE{$FORM{'Service'}})) {
  print <<EOF;
<TITLE>Products &amp; Services | DSL - Invalid Service</TITLE>
We do not currently have pricing for that type of service.
EOF
  print join('',`cat $ENV{'DOCUMENT_ROOT'}/stdftr.html`);
  print "</BODY>";
  exit;
}

$dsl=getDSL($FRM{"FRM_NPA"}, $FRM{"FRM_NXX"}, $FRM{"FRM_XXXX"},
            $FRM{"FRM_ADDR"}, $FRM{"FRM_CITY"}, $FRM{"FRM_STATE"},
            $FRM{"FRM_ZIP"});

print <<EOF;
Thank you for considering Access Internet Communications for your Internet
Service needs.  Since 1995 AIC has been an Internet Service Provider to both
the consumer and small to midsize business market.<P>
EOF

if($dsl==0) {
  print <<EOF;
<TITLE>Products &amp; Services | DSL - Service Unavailable</TITLE>
Based on your location, $FORM{Service} DSL is currently not available, we
expect to have service to this area in the near future as the coverage for
DSL grows.  Please feel free to check back with us on a monthly basis.<P>
EOF
  print <<EOF if($FORM{'Service'} eq 'Residential');
Another alternative you may want to consider is Business DSL.  Though this
service is for small busnesses you can order it for the home if you wish. 
To check availability of Business DSL in for area click
<A HREF="$0?FRM_NPA=$FRM{FRM_NPA}&FRM_NXX=$FRM{FRM_NXX}&FRM_XXXX=$FRM{FRM_XXXX}&FRM_ADDR=$FRM{FRM_ADDR}&FRM_CITY=$FRM{FRM_CITY}&FRM_STATE=$FRM{FRM_STATE}&FRM_ZIP=$FRM{FRM_ZIP}&Service=Business">here.</A><P>
EOF
} else {
  my $serv=lc $FORM{'Service'};
  my $table;
  print <<EOF;
<TITLE>Products &amp; Services | DSL - $FORM{Service} Service Available</TITLE>
Based on your location you qualify for our $serv service:<BR>
EOF
  foreach(sort keys %DSL) {
    my $type=$_;
    foreach(sort {$a<=>$b} @{$DSL{$_}}) {
      my $price=$PRICE{$FORM{'Service'}}{"$type $_"};
      if($price) {   
        $table.="<TR><TD>$type $_ Kbps</TD><TD>$price</TD></TR>";
        push(@options, "$type $_ Kbps");
      }
      $FORM{$type}.="$_,";
    }
    $FORM{$type}=~s/,$//;
  }
  print <<EOF if($table ne '');
<TABLE BORDER=1>
<TR BGCOLOR="#C6D6C6" ALIGN=CENTER><TD>Speed</TD><TD>Price</TD></TR>
$table;
</TABLE><BR>
EOF
  $accts="$FORM{Service} DSL";
  if($#options >= 0) {
    $accts="<SELECT name=speed><OPTION>";
    $accts.=join("<OPTION>",@options);
    $accts.="</SELECT>";
  }
  print <<EOF;
<FORM action=$next method=POST>
<TABLE>
<TR><TD ALIGN=RIGHT><INPUT type=submit name=form value="Order"></TD>
<TD>To sign up now for $accts service</TD></TR>
<TR><TD ALIGN=RIGHT><INPUT type=submit name=form value="Call Back"></TD>
<TD>To have a DSL representative phone you to further discuss your needs.</TD>
</TR></TABLE>
EOF
  $extras=~s/([^0-9A-Za-z])/sprintf("%%%02x",ord($1))/ge;
  print "<INPUT type=hidden name=extras value=$extras>" if($extras ne '');
  foreach(keys %FORM) {
    print "<INPUT type=hidden name=$_ value=\"$FORM{$_}\">";
  }
  print "</FORM>";
}
print join('',`cat $ENV{'DOCUMENT_ROOT'}/stdftr.html`);
print "</BODY>";
exit;

# Insufficient Info Response
# Put up a web page asking the user to complete the required fields.
# Remember to put a literal escape (backslash) in front of all quotes in the HTML

sub blank_response
{

print "<Head><Title>Products &amp; Services | Insufficient Information</Title></Head>";
print "<Body><H3>Sorry, your DSL pre-qualification form was <U>not</U> properly completed.</H3>";
print "In order to process your request, we need all the DSL location information.<P>";
print "Please use the \"Back\" command in your browser to return to the form and supply the necessary information.<P>";
print "If you wish to abandon the form, simply use the icons below to go on to any portion of the AIC Web Site or go back to the <A HREF=\"http://www.accesscom.com/\">AIC Home Page</A>";
print join('',`cat $ENV{'DOCUMENT_ROOT'}/stdftr.html`);
print "</BODY>";

exit;
}

use Socket;

sub getDSL {
  
  foreach(keys %PROVIDER) {
    $provider=$_;
    $regex=${$PROVIDER{$provider}[6]}{$FORM{'Service'}};
    next if($regex eq '' and $PROVIDER{$provider}[3] eq '');
    if(ref $PROVIDER{$provider}[2] ne 'CODE') {
      $postdata=sprintf($PROVIDER{$provider}[5], @_);
      $len=length($postdata)+1;
      socket(SOCKET, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
      connect(SOCKET, sockaddr_in(80, inet_aton($PROVIDER{$provider}[0])));
      select(SOCKET); $|=1; select(STDOUT);
      print SOCKET <<EOF;
POST $PROVIDER{$provider}[1] HTTP/1.0
Content-type: application/x-www-form-urlencoded
Content-length: $len
Authorization: Basic $PROVIDER{$provider}[2]

$postdata
EOF
    } else {
      &{$PROVIDER{$provider}[2]}(@_);
    }
    while(<SOCKET>) {
      if($PROVIDER{$provider}[3] ne '' and
         m/$PROVIDER{$provider}[3]/) {
        my $serv=$2;
        my $val=$1;
        grep { $serv=~s/$_/${$PROVIDER{$provider}[7]}{$_}/g; } (keys %{$PROVIDER{$provider}[7]});
        $extras.=sprintf("%s: %s\n", $serv, $val);
      }
      if($regex ne '' and m/$regex/) {
        my $speed=$1;
        my $service=$2;
        $speed*=1000 if($speed=~m/\./);
        grep { $service=~s/$_/${$PROVIDER{$provider}[7]}{$_}/g; } (keys %{$PROVIDER{$provider}[7]});
        @speed=( $speed );
        if(ref($PROVIDER{$provider}[4]) eq 'ARRAY') {
          grep { push(@speed, $_) if($_ < $speed); } @{$PROVIDER{$provider}[4]};
        }
        grep({s/$/\/${$PROVIDER{$provider}[8]}{$_}/}, @speed) if($service eq 'ADSL');
        if(ref($DSL{$service}) ne 'ARRAY') {
          $DSL{$service}=[ @speed ];
        } else {
          push(@{$DSL{$service}},@speed);
        }
      }
    }
    close(SOCKET);
  }

  return(keys %DSL);
}

sub npGet {
  ## get the session cookie ##
  socket(SOCKET, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
  select(SOCKET); $|=1; select(STDOUT);
  connect(SOCKET, sockaddr_in(80, inet_aton("prequal.northpointcom.com")));
  print SOCKET <<EOF;
GET /logon.asp HTTP/1.0

EOF
  while(<SOCKET>) {
    $cookie=$1 if(m/^Set-(Cookie: [^\s]*); /m);
  }
  close(SOCKET);
  
  ## log in to the session ##
  socket(SOCKET, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
  connect(SOCKET, sockaddr_in(80, inet_aton("prequal.northpointcom.com")));
  print SOCKET <<EOF;
POST /setuser.asp HTTP/1.0
$cookie
Content-type: application/x-www-form-urlencoded
Content-length: 34

user=megareseller&password=webxdsl
EOF
  while(<SOCKET>) {};
  close(SOCKET);
  
  $postdata="submitbutton=PreQual%20this%20address&FRM_NPA=$_[0]&FRM_NXX=$_[1]&FRM_XXXX=$_[2]&FRM_ADDR=$_[3]&FRM_CITY=$_[4]&FRM_STATE=$_[5]&FRM_ZIP=$_[6]";
  $len=length($postdata)+1;
  ## ask about the service ##
  socket(SOCKET, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
  connect(SOCKET, sockaddr_in(80, inet_aton("prequal.northpointcom.com")));
  print SOCKET <<EOF;
POST /GEOCODE.ASP HTTP/1.0
$cookie
Content-type: application/x-www-form-urlencoded
Content-length: $len

$postdata
EOF
}
