/* 
 *  Copyright 2007 IAC Search & Media.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

/*
 *  To Configure, use Directory, DirectoryMatch, Location, or LocationMatch:
 *  
 *  Something like this:
 *
 *  <LocationMatch /c/css/\d+/.*\.css$>
 *    NeverExpire on
 *  </LocationMatch>
 *
 */

#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_protocol.h"
#include "http_log.h"

#include "apr_strings.h"

#define MOD_NEVER_EXPIRE_VERSION "0.1.0"

module AP_MODULE_DECLARE_DATA never_expire_module;

typedef struct ne_conf_t {
    int enabled;
} ne_conf_t;

static int ne_handler(request_rec * r)
{
    ne_conf_t *conf;
    
    conf = (ne_conf_t *) ap_get_module_config(r->per_dir_config,
                                              &never_expire_module);
    if (conf && conf->enabled == 1) {

        if (apr_table_get(r->headers_in, "If-Modified-Since") != NULL ||
            apr_table_get(r->headers_in, "If-None-Match") != NULL) {
                return HTTP_NOT_MODIFIED;
        }
        else {
            /* We haven't sent this client the data before, but lets force
             * an insane expire timeout.
             */
            apr_table_set(r->headers_out, "Cache-Control", "public, max-age=315569260");
            /* XXXXXXX: change this when I turn 30. */
            apr_table_set(r->headers_out, "Expires", "Sun, 21 Dec 2014 13:33:33 GMT");
        }
        
    }
    return DECLINED;
}

static void ne_register_hooks(apr_pool_t * p)
{
    ap_hook_handler(ne_handler, NULL, NULL, APR_HOOK_FIRST);
}
                                                  
static const command_rec ne_cmds[] = {
    AP_INIT_TAKE1("NeverExpire", ap_set_flag_slot,
                  (void *) APR_OFFSETOF(ne_conf_t, enabled),
                  ACCESS_CONF,
                  "Enable Never Expire"),
    {NULL}
};


static void *ne_create_conf(apr_pool_t * p, char *dummy)
{
    ne_conf_t *conf = apr_pcalloc(p, sizeof(ne_conf_t));
    
    conf->enabled = 0;
    
    return conf;
}

module AP_MODULE_DECLARE_DATA never_expire_module = {
    STANDARD20_MODULE_STUFF,
    ne_create_conf,
    NULL,
    NULL,
    NULL,
    ne_cmds,
    ne_register_hooks,
};
