
/* This example show a CGI script in use
 *
 */
#include <rtos.h>
#include <net.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <graph.h>
#include <smtpcli.h>

#include <httpd.h>
#include <strlst.h>


crit_x *dos;

void web_showform( tcp_Socket *s )
{
    sock_puts( s, "<form method=\"post\" action=\"square\">"
                  "Enter a number "
                  "<input type=\"TEXT\" name=\"NUMBER\" value=\"23\">"
                  "<input type=\"submit\" value=\"Square\">"
                  "<input type=\"reset\"  value=\"Reset\">"
                  "</form>");
    html_tail( s );
}

void web_index( tcp_Socket *s )
{
    FILE *f;
    char buf[128];

    sock_puts(s, "Content-Type: text/html\r\n");
    html_hdr( s, "Simple CGI");
    web_showform( s );
}

void web_result( tcp_Socket *s )
{
    stringlist *sl;
    char *p, *q;
    DWORD x = 0;
    char buf[ 128 ];

    sock_puts(s, "Content-Type: text/html\r\n");

    sl = cgi_getstrings( s );

    if ( (p = strlst_findfirst( sl, "NUMBER", NULL, &q )) != NULL )
        x = atol( q );

    cgi_freestrings( sl );

    html_hdr(s,"Simple CGI");

    sprintf( buf, "<p>%lu squared is %lu</p>", x, x*x );

    sock_puts(s, buf );

    web_showform( s );

}
/*
 * - the web server calls this proc for each web request
 * - it is called in the context of *one* of the HTTPD threads,
 *   though which is not known or important
 * - multiple threads may be in the same proc at the same time
 */
void user_proc( tcp_Socket *s, char *cmd, char *file, char *ext )
{

    if ( !stricmp( file, "/" )) web_index( s );
    if ( !stricmp( file, "/square" )) web_result( s );
}

main()
{
    int i;
    kdebug = 1;
    rt_init(100);
    dos = cs_alloc();
    sock_init();            /* initialize network */

    cputs("starting...\r\n");

#define MAXHTTPD 5
    for ( i = 0 ; i < MAXHTTPD; ++i )
        rt_newthread( httpdthread, (DWORD)&user_proc, 8192, 0, "httpd worker" );
    do {
        /* nothing */
        rt_yield();
    } while ( 1 );
}

