
#include <stdio.h>

#include "mecha.h"

#include "htaccess_parser.h"

struct s_HtaccessParser
{
    char *filename;
    hshTvoid_list *data;
};

HtaccessParser *
htaccess_parser_new (const char *file)
{
    HtaccessParser *instance = (HtaccessParser *) malloc (sizeof (HtaccessParser));

    instance->filename = strFcopy (file);

    instance->data = hshFvoid_init (free);

    return (instance);
}

void
htaccess_parser_destroy (void *ptr)
{
    HtaccessParser *instance = (HtaccessParser *) ptr;

    free (instance->filename);

    hshFvoid_destroy (instance->data);

    free (instance);
}

const char *
htaccess_parser_get_value (HtaccessParser *instance, const char *key)
{
    return ((const char *) hshFvoid_find (instance->data, key));
}

bool
htaccess_parser_parse (HtaccessParser *instance)
{
    FILE *fp;
    char line[1024];

    fp = fopen (instance->filename, "r");

    if (fp == NULL)
    {
        return (false);
    }

    while (fgets (line, sizeof (line), fp) != NULL)
    {
        char *firstSpace;

        strFstrip_crlf (line, strlen (line));

        firstSpace = index (line, ' ');

        if (firstSpace == NULL)
        {
            logFmsg (CONT_LOG_WARN, "htaccess: unknown line: %s", line);
        }

        *firstSpace = 0;

        firstSpace++;

        if (*firstSpace == '"')
        {
            firstSpace++;
        }

        {
            int secondLength = strlen (firstSpace);



            if (firstSpace[secondLength - 1] == '"')
            {
                firstSpace[secondLength - 1] = 0;
            }
        }

        hshFvoid_add (instance->data, line, strFcopy (firstSpace));
    }

    fclose (fp);

    return (true);
}
