#!/afs/athena/contrib/perl/p

require '/afs/sipb/user/mkgray/bin/http.pl';
$projdir = "$ENV{'HOME'}/project/" unless $projdir = $ENV{'PROJECT_DIR'};
&http'httpd();

sub user_input {
    local($n, $text) = @_;
    ($request, @headers) = split("\n\r", $text);
    ($method, $file, $proto, @trash) = split(" ", $request);

    $file =~ /\?(.+)/;
    $form = $1;
    $form=~s/\+/ /g;
    %formr = &parseform($form);
    $send = '';

    print("$method $file $proto\n");
    if(defined $formr{'edit'}){
	print("Edit!\n");
    }
    else{
	print("Giving todo list\n");
	&todo("");
    }

    if($proto eq "HTTP/1.0"){
	$type = 'text/html';
	&sendit($n, $send);
    }
}

sub todo {
    local($dir) = @_;
    $/ = '';
    open(TODO, $projdir.$dir."Todo") || print "Can't open $projdir$dir"."Todo";
    $todo = <TODO>;
    close(TODO);

    $send .= ("<pre>$todo</pre>");
    $send .= ("<hr>");
    $send .= ("<form><input type=hidden name=edit value=$dir><input type=submit value=Edit></form><p>");

}

sub load_db {
    $projdb = "/tmp/projdb" unless $projdb = $ENV{'PROJDB'};

    $/ = "";
    open(NDB, $projdb) || return;
    while(<NDB>){
        ($notename, $note) = split("", $_);
        $proj{$notename} = $note;
    }
    @nnames = keys %proj;
    @nbodys = values %proj;
    $numproj = $#nnames;
}

sub save_db {
    rename($projdb, "/tmp/dbtmp");

    open(NDB, ">>$projdb");
    for $note (@nnames){
        print(NDB "$note$proj{$note}");
    }
    close(NDB);
}
sub parseform {
    local($formthing) = @_;     # Expects something like:
                                # foo=wow%21&bar=hello&baz=blah

    (@fields) = split('&', $formthing);
    for $f (@fields){

        ($name, $value) = split('=', $f);
            $value =~ y/\+/ /;
        $value =~ s/%([\da-f]{1,2})/pack(C,hex($1))/eig; # remove % escapes
        if(defined $lookup{$name}){
            $lookup{$name} .= "\n".$value;
            }
        else{
          $lookup{$name} = $value;
    }
    }

    %lookup;
}

sub sendit {
    local($n, $send) = @_;
    &http'tell("HTTP/1.0 200 OK\n", $n);
    &http'tell("Content-type: ".$type."\n", $n);
    &http'tell("Content-length: ".length($send)."\n", $n);
    &http'tell("\n", $n);
    &http'tell($send, $n);
}
