/*
 * http_d.c web server with Server Side Includes to generate
 *                     dynamic content, and a cookie example
 */
#include <rtos.h>
#include <net.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <httpd.h>
#include <mem.h>

void ShowCoreLeft( tcp_Socket *s, stringlist *unused )
{
    char buffer[64];

    sprintf( buffer, "%lu", coreleft() );
    sock_puts( s, buffer );
}

void ShowTime( tcp_Socket *s, stringlist *unused )
{
    time_t now;
    char buffer[ 128 ];

    dos_enter();
    time( & now );
    strcpy( buffer, ctime( &now ));
    dos_exit();

    sock_puts( s, buffer );
}


void ShowCookie( tcp_Socket *s, stringlist *cookies )
{
    char *p;
    void *x;

    p = strlst_findfirst( cookies, "ourcookie", &x, NULL );
    sock_puts( s, p );
}


static ssi_type ssi_list[] =
  { { "coreleft", ShowCoreLeft },
    { "time",     ShowTime },
    { "showcookie",ShowCookie },
    { NULL, NULL }
    };

/***********************************************************************
 * - 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,
    stringlist *cookies )
{
    /* prepare output */
    sock_puts( s, "Content-Type: text/html");
    sock_puts( s, "Set-Cookie: ourcookie=flub\r\n");
    
    if ( !stricmp( file, "/" ))
        http_shtml( s, "web", "index","sht", ssi_list, cookies );
    else if ( !stricmp( ext, "sht" ))
        http_shtml( s, "web", file, ext, ssi_list, cookies );
    else
        http_dump( s, "web", file, ext );
}


main()
{
    int i;

    kdebug = 1;
    rt_init(100);
    kpreemptive = 1;        /* enable pre-emptive multithreading */
    sock_init();            /* initialize network */

    cputs("starting...\r\n");
#define MAXHTTPD 5
    for ( i = 0 ; i < MAXHTTPD; ++i )
        rt_newthread( httpdthread, (DWORD)&user_proc, 4096, 0, "httpd worker" );
    do {
        /* nothing */
        rt_yield();
    } while ( 1 );
}


