#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <ctype.h>

#include "global.h"
#include "survey.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_survey_util.h"
#include "manhat-lib/shared_super_key.h"

#include "manhat-lib/shared_survey_string.h"
#include "manhat-lib/shared_survey_path_util.h"
#include "manhat-lib/shared_survey_update_info.h"
#include "manhat-lib/shared_lock.h"
#include "manhat-lib/shared_survey_reuse_util.h"
#include "manhat-lib/shared_user_index.h"
#include "manhat-lib/shared_survey_www_util.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_server_string.h"


void
read_parameters( int *is_admin, char *key, char *count, char *title, int *public, char *username)
{
     char tmp[10];

     cs_get_required_parameter("id", key, MAX_KEY);
     cs_get_required_parameter("count", count, MAX_PATH);
     cs_get_optional_parameter("admin", tmp, 9);
     *is_admin = !*tmp? 0 : atoi(tmp)? 1: 0;
     cs_get_required_parameter ("linkTitle", title,  MAX_PATH);

     cs_get_optional_parameter("public", tmp, 9);
     switch(*tmp)
     {
      case '1': *public = 1;
                break;
                
      case '2': *public = 0;
                cs_get_required_parameter ("getter", username,  MAX_USERNAME); 
                break;
                
      case '3': *public = 2;
                 break;

      default:   *public = -1;
                 break;
     }           
                 
}





void
write_to_shared_list_file(const char *count, SESSION *user, const char *username)
{
    char filename[MAX_PATH +1];
    char survey_path[MAX_PATH +1];
    FILE *fp;

    get_survey_path(user, survey_path, count); /*shared_survey_path_util.c */
    snprintf(filename, MAX_PATH +1, "%s/%s", survey_path, SURVEY_SHARED_FNAME);
    fp = fopen(filename, "a+");
    if(!fp)
	cs_critical_error(ERR_FOPEN_WRITE_FAILED, "");
    get_exclusive_lock(fileno(fp), 1);
    fprintf(fp, "%s\n", username);
    release_lock(fileno(fp));
    fclose(fp);
}





void
shared_survey_with_x(const char *username, const char *count, SESSION *user)
{
    char shared_dir[MAX_PATH +1];
    char shared_survey_count[MAX_PATH +1];
    char org_survey_path[MAX_PATH +1];
    SURVEY_INFO *info;

    snprintf(shared_dir, MAX_PATH +1, "../%s/%s", SURVEY_DIR, username);
    mkdir(shared_dir, 0770);
    get_survey_id(shared_survey_count,shared_dir); /* shared_survey_util.c */

    /* shared_survey_reuse_util.c */
    create_new_survey_dir(shared_dir, shared_survey_count); 
    org_survey_path[0] = '\0';
    info = get_survey_info(count, shared_survey_count , user, org_survey_path, "", username,0, 1); 

    if(strlen(org_survey_path) >0)
      copy_survey_file(org_survey_path,  shared_survey_count, user, username, 0);
    else
      cs_critical_error(ERR_COPY_ERROR, "");
     record_survey_info(info, user, username, 0); /* shared_survey_reuse_util.c */
     free_survey_info(info); /* shared_survey_info_parser.h */
    write_to_shared_list_file(count, user, username);
}




int
validate_username(const char *username, char *realname)
{
     char *buffer;
     char *start_search, *ptr, *ptr2;
     int found =0, search_len;

     search_len = strlen(username);
     /* read the entire users/index.txt file into a null-terminated buffer */
     buffer_index(&buffer);   /* shared_user_index.c */
     start_search = buffer;
     
     while(!found)
     {
         ptr = strstr(start_search, username);
         if(ptr)
	 {
            found = *(ptr + search_len) == ':' &&
               (ptr2 = strchr(ptr+search_len+1, ':'));
            if(!found)
	      start_search = ptr +1;
	 }
	 break;
     }
    if(buffer)
      free(buffer);
   return found;
}



void
write_xml_result(const char *survey_base)
{
   char file[MAX_PATH +1];
   FILE *fp;

   snprintf(file, MAX_PATH +1, "%s/%s",survey_base, SURVEY_RESULT_FNAME);
   fp = fopen(file, "w");
   if(!fp)
      cs_critical_error(ERR_FOPEN_WRITE_FAILED, "");
   fprintf(fp, "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>\n");
   fprintf(fp, "<records>\n");
   fprintf(fp, "  <expect_takers>%d</expect_takers>\n", 0);
   fprintf(fp, SURVEY_RESULT_END_TAG);
   fclose(fp);
}



int
get_password()
{
   int seed, i;
   seed = time(NULL);
   srand(seed);
   i = 100000+(int)(900000.0 *rand()/(RAND_MAX + 1000000.0));

   return i;
}

	          	       

void
copy_to_www(SESSION *user, const char *count, char *new_survey_id, int *password)
{
     char base_dir[MAX_PATH +1];
     char new_survey_dir[MAX_PATH +1];
     char com[MAX_PATH +1];
     FILE *fp;

     snprintf(base_dir, MAX_PATH +1, "../%s/%s", SURVEY_DIR, SURVEY_WWW_DIR);
     mkdir(base_dir, 0770);
     get_survey_id(new_survey_id, base_dir);
     snprintf(new_survey_dir, MAX_PATH +1, "%s/%s", base_dir, new_survey_id);
     mkdir(new_survey_dir, 0770);
     get_survey_path(user, base_dir, count);
     snprintf(com, MAX_PATH +1, "cp %s/%s %s/%s",
	    base_dir, SURVEY_XML_FNAME, new_survey_dir, SURVEY_XML_FNAME);
     system(com);
     write_xml_result(new_survey_dir);
     update_survey_info_state(user,  count, SURVEY_STATE_WWW,"",new_survey_id);

     *password = get_password();
     snprintf(base_dir, MAX_PATH +1,"%s/%s", new_survey_dir, PASSWORD_FNAME);
     fp = fopen(base_dir, "w");
     if(!fp)
        cs_critical_error(ERR_FOPEN_WRITE_FAILED, "");
     fprintf(fp, "%d", *password);
     fclose(fp);

} 




void
do_action(SESSION *user,  const char *count, char *title,
	   int public, const char *username)
{
     int found, password;
     char realname[MAX_NAME +1], new_id[MAX_PATH +1];

     if(public == -1)
     {
	decode_space(title);
	cs_set_value("linktitle", title);
	cs_cgi_display("survey_public_form", 1);
     }
     else if(public == 1)   /* make survey public */
     {
        update_survey_info_state(user,  count, SURVEY_STATE_PUB,"", "");
	decode_space(title);
	cs_set_value("linktitle", title);
	cs_set_value("success_code", SURVEY_PUBLIC_CODE);
	cs_cgi_display("survey_success", 1);
     }
     else if(public == 0) /* give survey to teacher */
     {

       found =  validate_username(username, realname);
       if(!found)
	 cs_critical_error(ERR_INVALID_USER, "");
       else
       {
         shared_survey_with_x(username, count, user);
	decode_space(title);
	cs_set_value("linktitle", title);
	cs_set_value("success_code", SURVEY_SHARED_CODE);
	cs_cgi_display("survey_success", 1);
       }
     }
     else 
     {
	copy_to_www(user, count, new_id, &password);
	cs_set_value("linktitle", title);
	set_url(new_id, password);  /* shared_survey_www_util.c */
	cs_cgi_display("survey_www_info", 1);
     }
} 


   


int main()
{
   int is_admin;      /* if 1 then an admin is running the program, if 0 
                      ** it's a teacher 
                      */
                
   char key[MAX_KEY +1];
   char count[MAX_PATH +1];
   char title[MAX_PATH +1];
   char username[MAX_USERNAME +1];
   int public;
   SESSION user;
 
   cs_cgi_init();  
   read_parameters(&is_admin, key, count, title, &public, username);
   if(is_admin)
      validate_super_key(key, &user);
   else
      cs_critical_error(ERR_REQUEST_DENIED, "");
         
   do_action(&user,  count, title,public, username);
   cs_cgi_destroy(); 
  return 0;
} 

