#!/usr/bin/perl -w

use strict;
use lib '.';
use LWP::Daemon;
use LWP::MainLoop qw(mainloop);

my $m = new SmallHttpd;

my $d = new LWP::Daemon (
    ManagedBy => $m,
);

print "LWP::Daemon returned. i am ", $d->url, "\n";
mainloop->run;

die "Mainloop terminated";

package SmallHttpd;
use Socket;
use HTTP::Status;
use HTTP::Response;

# dummy, no class data
sub new {
    bless [], shift;
}

sub server_init {
    my($self, $sock, $url) = @_;

    print "server_init with url: $url\n";
}

#sub incoming_connection {
#    my($self, $serversock, $newsock, $peeraddr) = @_;
#
#    my($port, $ip) = unpack_sockaddr_in($peeraddr);
#    print "Incoming connection on $newsock addr: ", inet_ntoa($ip), ":$port\n";
#}

#sub new_request_header {
#    my($self, $sock, $req) = @_;
#
#    print "Got a complete request HEADER from $sock:\n";
#    print $req->as_string;
#    # we don't want to take over
#    0;
#}

sub new_request {
    my($self, $sock, $req) = @_;

    print "Got a complete request from $sock:\n";
    print $req->as_string;

    my $url = $req->url;
    my $res = new HTTP::Response(RC_OK);
    $res->push_header('Content-Type' => 'text/html');
    $res->push_header('X-Useless-Header' => 'yes');
    $res->content(<<HTML);
<html>
<head>
<title>Testing</title>
</head>
<body bgcolor="#ffffff">
<h1>Test</h1>
<p>This is just a test, you asked for $url</p>
</body>
</html>
HTML
    $sock->send_response($res);
}
