#!/usr/bin/perl
use strict;
use warnings;

use Data::Dumper qw(Dumper);
use HTTP::Daemon;
use HTTP::Status;
use Getopt::Long qw(GetOptions);

use FindBin qw($Bin);
use JSON qw(to_json);


my $port     = 8080;
my $hostname = 'localhost';
my $help;

GetOptions(
    "port=s"     => \$port,
    "host=s"     => \$hostname,
    "help"       => \$help,
);

if ($help) {
    usage();
}

my $daemon = HTTP::Daemon->new(
        LocalAddr => $hostname,
        LocalPort => $port, 
        ReuseAddr => 1,
    ) or mydie();

logger("Please contact me at: <" . $daemon->url . ">");

while (my $connection = $daemon->accept) {
    while (my $r = $connection->get_request) {
        if ( $r->method ne 'GET' ) {
            $connection->send_error(RC_FORBIDDEN);
            next;
        }

        if ( $r->url->path =~ m{^/(\w+\.(html|js|css))?$} or $r->url->path eq '/jquery-1.11.0.min.js' ) {
            my $file = substr($r->url->path, 1);
            $file ||= "index.html";
            $file = "$Bin/html/$file"; 
            logger("Requested file: $file");
            $connection->send_file_response($file);
        } elsif ( $r->url->path =~ m{^/add$} ) {
            my $result = _add_ab($r->url->query);
            my $response = HTTP::Response->new(RC_OK, '', 
                    ['Content-type' => 'application/json'], to_json { result => $result });
            $connection->send_response($response);
 
        } elsif ( $r->url->path =~ m{^/cgi/cgi_sum.pl$} ) {
            my $html = add_ab($r->url->query);

            my $response = HTTP::Response->new(RC_OK, '', 
                    ['Content-type' => 'text/html'], $html);
            #logger($response->is_success . $response->content);
            $connection->send_response($response);
=pod
            elsif ( $r->url->path =~ m{^/cgi/\w+(\.\w+)?$} ) {
                my $file = substr($r->url->path, 1);
                $file = "$Bin/$file"; 
                logger("Requested CGI file: $file");
                logger("Requested url path: ". $r->url->path);
                logger("Requested url query: ". $r->url->query);
                #logger("Requested Content: ". $r->content);
                #logger("Requested as_string: ". $r->as_string);
                
                local $ENV{QUERY_STRING} = $r->url->query;
                my @result = `$file`;

                # drop header generated by CGI script
                while (@result and $result[0] =~ /\S/) {
                    shift @result;
                }
                my $response = HTTP::Response->new(RC_OK, '', 
                        ['Content-type' => 'text/html'], join "", @result);
                #logger($response->is_success . $response->content);
                $connection->send_response($response);
            }
=cut

        }
        else {
            logger("Invalid path: " . $r->url->path);
            $connection->send_error(RC_NOT_FOUND)
        }
    }
    $connection->close;
    undef($connection);
}

sub mydie {
    die <<"END_DIE";
Could not start Daemon
Please make sure $hostname is pingable and resolves to 127.0.0.1
END_DIE
}

sub logger {
    my ($str) = @_;
    print "$str\n";
}

sub _add_ab {
    my ($query) = @_;

    my %params;
    my @pairs = split /&/, $query;
    foreach my $p (@pairs) {
        my ($k, $v) = split /=/, $p;
        $params{$k} = $v;
    }
    #warn Dumper \%params;
    if ($params{sleep}) {
        sleep $params{sleep};
    }

    $params{a} ||= 0;
    $params{b} ||= 0;
    return $params{a} + $params{b};
}

sub add_ab {
    my $result = _add_ab(@_);

    my $html = <<"END_HTML";
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Result</title></head>
<body>
<h1 align="center">$result</h1>
</body>
</html>
END_HTML

    return $html;
}

sub usage {
    print <<"END_USAGE";
$0
    --help          this help
    --port PORT     port number (usually > 1024, defaults to $port)
    --host HOST     host name (needs to be pingable, defaults to $hostname)
END_USAGE
    exit;
}
