#!perl
@ORIGARGV = @ARGV;

require "set.pl";
require "netserver.pl";
require "httpserver.pl";
require "file.pl";
require "configfile.pl";
require "stash.pl";
require "calendar.pl";

sub domonth {
    my ($db,$obj,$pw) = @_; 
    my $x;
    &HTML::print_head("$db month $obj/1996");
    $obj = CALENDAR::month2num($obj);
    print "<pre>\n";
    $x=`cal $obj 1996`;
    $x =~ s#\b(\d{1,2})\b#<a href="date=1996.$obj.$1">$1</a>#g;
    print "$x</pre>$HTML::tail\n";
}
sub dodate {
    my ($db,$obj,$pw) = @_; 
    my ($thisday) = &CALENDAR::parsedate($obj);
    local(%days);
    &HTML::print_head("$db day $obj ($thisday)");
    print "<pre>\n";
    tie %days, STASH, $db;
    if (exists $days{$thisday}) {
	print $days{$thisday};
    } else {
	print "nothing for today\n";
    }
    print "</pre>\n";
    &HTML::make_buttons($thisday, [["edit"=>"Edit"],["add"=>"Add"]]);
    local $m = unpack("xxxxA2xx",$thisday);
    print qq{<a href="month=$m">$CALENDAR::months[$m-1]</a>\n};
    print "$HTML::tail\n";
}

sub doadd {
    my ($db,$obj,$pw) = @_; 
    my ($thisday) = &CALENDAR::parsedate($obj);
    local(%days);
    &HTML::print_head("Add $db day $obj ($thisday)");
    print "Enter the note and Submit to add it<p>\n";
    &HTML::testform("note", "rows=1 cols=60");
    print "$HTML::tail\n";
}

sub postadd {
    my ($database, $tag, $pw, $content) = @_;
    local($thisday) = &CALENDAR::parsedate($tag);
    local(%days);
    tie %days, STASH, $database;
    $days{$thisday} .= ${$content}{"body"};
    &HTML::print_status_page("stored entry for $tag ($thisday)");
}


$HTTP::SERVER::subgetverbs = {
    "month" => \&domonth,
    "date" => \&dodate,
    "add" => \&doadd,
};
$HTTP::SERVER::subgetpaths = {
#    "/allpages" => \&printallpages, 
    "/" => sub { my $db = shift;
		 &HTML::print_head("calendar test server for $db");
		 print qq{
<p>
<a href="/calendar/month=2">february</a>
$HTML::tail
};
	     },
};
$HTTP::SERVER::subpostverbs = {
    "add" => \&postadd,
};
$HTTP::SERVER::dbpaths{"calendar"} = "calendartest";

sub HTTP::SERVER::checkpassword { #  database tag content{pw}
    local($db,$tag,$pw) = @_;
    return 1;
#    return 1 if !defined $master_password;
#    return 1 if $pw eq $master_password;
#    return 0;
}

sub main {
    &HTTP::SERVER::serverloop($port, $conffile);
}

die "usage: $0 conffile portnumber" if @ARGV < 1;
$conffile = shift;
$port = 7999;
$port = shift if (@ARGV > 0);
$master_password = "foo";

&main;
