#include <stdio.h>
#include <string.h>
#include <sys/stat.h>		/* for stat() */
#include <unistd.h>		/* for unlink() */

#include "global.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_bio.h"
#include "manhat-lib/shared_person_list.h"

/** Course is an optional parameter.  If course is sent,
*** the the user is working within a Manhattan course.
*** Otherwise, they are working from the My Manhattan page.
***/

static void
read_parameters (char *course, char *key)
{
  cs_get_required_parameter ("id", key, MAX_KEY);
  cs_get_required_parameter ("crs", course, MAX_PATH);
}



    


static void
set_person_data(P_NODE *person, const char *course, const char *key, CONFIG_STRUCT *conf, SESSION *user)
{
#define MAX_TMP_NAME 30 
 char bio_dir[MAX_PATH + 1];
 char url[MAX_PATH +1];
 char name[MAX_TMP_NAME];
 static int number_processed = 0;

 get_bio_dir(course, conf, person->data.username, bio_dir);    /* shared_bio.c */
    
  snprintf(url, MAX_PATH +1, "%s?id=%s&amp;crs=%s&amp;user=%s",
            "bio_send_photo",
            key,
            course,
            person->data.username);
  snprintf(name, MAX_TMP_NAME, "user.%d.photo_url", number_processed);
  cs_set_value(name, url);  
 
 if(!strcmp(person->data.id, user->id) || bio_exists(bio_dir))   /* shared_bio.c */
  {
    snprintf(url, MAX_PATH +1, "%s?id=%s&amp;user=%s&amp;crs=%s",                 
           "bio_view",
           key,
           person->data.username,
           course);
    snprintf(name, MAX_TMP_NAME, "user.%d.view_bio_url", number_processed);
    cs_set_value(name, url);  
  }
  snprintf(name, MAX_TMP_NAME, "user.%d.realname", number_processed);
  cs_set_value(name, person->data.realname);  
 
  number_processed++;
 
 
 #undef MAX_TMP_NAME  
 
}     
     
     
                  
           
         
static 
void list_bios (const char *course, const char *key, SESSION *user, CONFIG_STRUCT *conf)
{

 P_NODE *head, *ptr;
 

 head = build_option_person_list(conf);   /* shared_person_list.c */
 
 cs_set_course_info(conf);
 cs_set_current_time(); 

 for(ptr = head; ptr; ptr=ptr->next)
    set_person_data(ptr, course, key, conf, user);
 free_option_person_list(head);  /* shared_person_list.c */    

}







int
main ()
{
  char course[MAX_PATH + 1];	            /* from crs=? command line */
  char key[MAX_KEY + 1];	            /* from id=? command line */
  SESSION user;
  CONFIG_STRUCT conf;		            /* the configuration read from config file */

  cs_cgi_init();

  read_parameters (course, key);
  read_configuration_file(course, &conf);   /* shared_util.c */
  validate_key (key, &user, &conf);	    /* shared_util.c */
  


  if(!conf.people && (user.group == STUDENT))
       cs_critical_error(ERR_REQUEST_DENIED, "");

  list_bios (course, key, &user, &conf);
  
  cs_cgi_display("bio_list", 1);
  cs_cgi_destroy(); 
  return 0;			/* exit successfully */

}

