#!/usr/bin/perl -w

use CGI;

use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
use constant BUFFER_SIZE => 4_096;
use strict;

my $command_file = "/tmp/validation_commands.txt";
my $validation_file = "/tmp/validation_results.txt";

my $username = "";
my $password = "";

#----------------------------
# grab the user data
#----------------------------
my $userData = new CGI;
$username = $userData->param('username');
$password = $userData->param('password');

#----------------------------
# create the sqlite3 command file to look for the specified user
#----------------------------
open COMMAND_FILE, '>'.$command_file;
print COMMAND_FILE ".output $validation_file\n";
print COMMAND_FILE "select * from new_users where User_Name=\"$username\" and Password=\"$password\";\n";
print COMMAND_FILE ".exit";
close COMMAND_FILE;

#----------------------------
# run the command file and make sure we got something in return
#----------------------------
system("sqlite3 /nautel/userdatabase/userDatabase.db < $command_file");

my $file_size = int(-s "$validation_file");
if ($file_size)
{
#----------------------------
# if the specified user is in the database, create the log tar file and send it to the user
#----------------------------

   my $buffer = "";
   my $tar = "/bin/tar";
   my $compress = "/usr/bin/compress";
   my $fileName = "/tmp/NautelLogs.tar";

   my $cgi = new CGI;

   print $cgi->header(-type => "application/octet-stream",
                   -expires => "-1d",
                   -attachment => "NautelLogs.tar" );

   binmode STDOUT;

   system("$tar", "-cf", "$fileName", "-C", "/", "var/log", "nautel/logs");

   open(TARBALL, $fileName);
   while ( read( TARBALL, $buffer, BUFFER_SIZE ) ) {
       print $buffer;
   }
   close TARBALL;
}
else
{
#----------------------------
# if the specified user isn't in the database, provide feedback
#----------------------------
print "Content-type: text/html\n\n";

print <<"EOF";
<HTML>

<HEAD>
<TITLE>Nautel Logging - invalid credentials</TITLE>
</HEAD>

<BODY>
Incorrect username/password.  Please try again.
</BODY>

</HTML>
EOF
}
