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



#include "../global.h"
#include "../custom.h"

#include "shared_util.h"
#include "shared_strtrm.h"
#include "shared_cs_util.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 cookie[MAX_COOKIE + 1];
 char *cookie_ptr;
 char *ptr, *ptr2;
 int name_len;
 
 name_len = strlen(COOKIE_NAME);

 
 cookie_ptr = getenv("HTTP_COOKIE");
 if(!cookie_ptr)
  {
    return 0;    
  }  
 
 strncpy(cookie,cookie_ptr, MAX_COOKIE + 1);
 *(cookie + MAX_COOKIE) = '\0';


 ptr = strstr(cookie,COOKIE_NAME);
 if(!ptr)
  {
     return 0;
  }
     
 if(strlen(ptr) < name_len)
   {
     return 0;
   }
          
 ptr += name_len;

 ptr2 = strchr(ptr,';');  
 if(ptr2)
     *ptr2 = '\0';
      
 strncpy(key, ptr,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 *str;
    
    str = hdf_get_value(global_cgi->hdf, "CGI.ServerName", "");
    printf("Content-type: text/html\n");
    printf("Set-Cookie: %s%s; PATH=/%s; DOMAIN=%s%s\n",COOKIE_NAME,key,path1,str,SECURE_COOKIES?"; secure":"");
    
    if(*path2)
          printf("Set-Cookie: %s%s; PATH=/%s; DOMAIN=%s%s\n",COOKIE_NAME, key,path2,str,SECURE_COOKIES?"; secure":"");
    
    printf("\n");

}



