/* twsws.cpp
   The World's Smallest Web Server main module */

#include <stdlib.h>
#include <unistd.h>
#include "logging.h"
#include "Server.h"

const char* USAGE = {"twsws version 1.1\nUSAGE: twsws [-p port] [-l log_path] directory\n"
"\n"
"Serves the directory specified.  Listens on optional port parameter, which\n"
"defaults to 80.  Log output is written to log_path, if specified.\n"
"\n"
"The file extensions which are currently recognised are limited to those listed\n"
"in EntityType.cpp.  Any other extension is not served up for extra security.\n"
"\n"
"Examples:\n"
"\n"
"\ttwsws .\n" 
"\ttwsws -p 8080 -l /tmp/twsws.log /home/fred/wwwroot\n\n"};

char* get_option(int argc, char* argv[], char marker)
{
    for (int i = 1; i < argc - 1; i++) {
        if (argv[i][0] == '-') {
            if (argv[i][1] == marker) {
                return argv[i+1];
            }
        }
    }
    return NULL;
}

char* get_param(int argc, char* argv[])
{
    for (int i = 1; i < argc; i++) {
        if (argv[i][0] == '-') {
            i++;
            continue;
        }
        return argv[i];
    }
    return NULL;
}

int main(int argc, char* argv[])
{
    if (argc < 2 || argc > 6) {
        printf(USAGE);
        exit(-1);
    }
    int port = 80;
    char* port_str = get_option(argc, argv, 'p');
    if (port_str != NULL) {
        port = atoi(port_str);
        if (port <= 0) {
            abort("Invalid port number: %d", port);
        }
    }
    char* log_path = get_option(argc, argv, 'l');
    char* root_path = get_param(argc, argv);
    if (root_path == NULL) {
        abort("No root directory specified.");
    }
    
    if (chdir(root_path) < 0) {
        abort("Failed to chdir to %s", root_path);
    }
    if (log_path != NULL) {
        log_init(log_path);
    }
    log("Starting the smallest web server in the world");
    Server* ws = new Server();
    ws->run(port);
}