#include <stdio.h>
#include <string.h>
#include <stdlib.h>



#include "../global.h"

#include "shared_util.h"
#include "shared_strtrm.h"
#include "shared_cs_util.h"
#include "shared_system_data.h"

/** reads the HTTP_COOKIE environment variable 
*** and parses out the id=xxxxx portion, returning it
*** as 'key'.
*** returns 1 on success, else returns 0
***/

#define COOKIE_NAME "mvcid"


int parse_cookie(char *key)
{

 char *mycookie;
 char cookie_name[100];
 
 snprintf(cookie_name, 100, "Cookie.%s", COOKIE_NAME);

 mycookie = hdf_get_value(global_cgi->hdf, cookie_name, "");
 if(strlen(mycookie) ==0)
    return 0;
 strncpy(key, mycookie, MAX_KEY + 1);
 *(key + MAX_KEY) = '\0';
 strtrm(key);      /* shared_strtrm.c */
 return 1;
}    
 

void set_cookie(const char *key, const char *path1, const char *path2)
{
  
   char path[MAX_PATH +1];
   char *str;
   char name[MAX_PATH +1];
   int secure =0;

   str = hdf_get_value(global_cgi->hdf, "CGI.ServerName", ""); 
   snprintf(name, MAX_PATH +1, ".%s", str);
   snprintf(path, MAX_PATH +1, "%s%s%s", *path1 == '/' ? "":"/", path1, path1[strlen(path1) -1] == '/'?"":"/");   
   
   if(*path2)
      secure = system_data_int("SUPER_SECURE_COOKIES");
   else
      secure = system_data_int("SECURE_COOKIES");

   cgi_cookie_set(global_cgi, COOKIE_NAME, key, path, name, "", 0, secure);
}



