#include <stdio.h>
#include <stdlib.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_super_util.h"
#include "manhat-lib/shared_bio.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, char *username, int *is_admin)
{
  char tmp[10 + 1];


  cs_get_required_parameter ("id", key, MAX_KEY);
  cs_get_required_parameter ("user", username, MAX_USERNAME);
  cs_get_optional_parameter ("crs", course, MAX_PATH);
  cs_get_optional_parameter ("admin", tmp, 10);
  if(strlen(tmp))
     *is_admin = 1;
  else
     *is_admin = 0;
}



/** returns 1 if photo for target_username was sent properly,
*** else returns 0
**/

static 
int photo_sent (const char *course,   /* this could be and empty string */
              CONFIG_STRUCT *conf,   /* contains junk if course is an empty string */
              const char *target_username)   /* username whose profile we're displaying */
{

 char bio_dir[MAX_PATH + 1];
 char photo_path[MAX_PATH + 1];
 FILE *fp;
 struct stat statbuf;
 char *buffer;
 
  /* bio info is either stored in ../users/x/username/bio or, for standalone courses in
  ** course_dir/people/username/bio
  */     
  get_bio_dir(course, conf, target_username, bio_dir);       /* shared_bio.c */
 

  snprintf(photo_path,MAX_PATH + 1, "%s/%s", bio_dir, BIO_PIC_FNAME);
  if (stat (photo_path, &statbuf)) /* then photo doesn't exist */
       return 0;                  /* send didn't work */
       
  if(!statbuf.st_size)
     return 0;                    /* file has zero length */
          
  buffer = (char *) malloc(statbuf.st_size * sizeof(char));
  if(!buffer)
         return 0;                /* malloc failed - send didn't work */

   fp = fopen(photo_path, "r");
   if(!fp)
         return 0;               /* can't open file - send didn't work */


  if(fread(buffer,statbuf.st_size,1,fp) != 1)
    {
     fclose(fp);
     return 0;      /* read error */
    }    
        
  fclose(fp);

  printf("Content-type: image/jpeg\n\n");      
  fwrite(buffer, statbuf.st_size, 1, stdout);
  free(buffer);
  return 1;
} 
 


static
void send_no_photo_image()
{
 /* global_theme is in shared_cs_util.c */
 printf("Location: %s/%s%d/%s\n\n", IMAGE_PATH, THEME_DIR_PREFIX, global_theme, NO_PHOTO_FNAME);
}

 
 


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

  cs_cgi_init();

  read_parameters (course, key, target_username,&is_admin);
  
  /** This program can be run by:
  ***   A teacher or student from their "My Manhattan Page":
  ***       - The 'course' string should be empty
  ***       - call validate_server_key()
  ***       - we know it's not a standalone course
  ***       - later, we'll check to make sure their username matches the target_username
  ***           since, users should only be allowed to see their own profile.
  ***
  ***   A teacher or student from within a particular Manhattan classroom's People module
  ***       - The course is contained within the 'course' string
  ***       - We read the course's config file to determine whether or not the course is a standalone course
  ***       - call validate_key()
  ***       - both this user and the target_username must be members of this course
  ***           (so people can't randomly view profiles of people in other courses)
  ***
  ***   An admin running the program from the administrative interface, or from within the Config menu of
  ***   a course:
  ***         - An admin=1 parameter is passed via the CGI, and sets is_admin to true
  ***         - there may or may not be a non-empty course string.  It can be empty if the admin is accessing
  ***             the program from View/Modify users.  It will be non-empty if the admin is accessing the
  ***             program from within a course's Config menu
  ***         - we validate_super_key()
  **/


  /* If a course was provided on the command line, read its configuration file.
  ** Set whether or not we're dealing with a standalone course
  **/

  if(*course)
     read_configuration_file(course, &conf);
     

 /* validate the appropriate key */
  if(is_admin)
   {
    if (!*course)
       validate_super_key(key, &user);     /* shared_super_util.c */
    else
       validate_key (key, &user, &conf);	/* shared_util.c */
   }      
  else if(!*course)
    validate_server_key(key, &user);       /* shared_util.c */
  else
    validate_key (key, &user, &conf);	/* shared_util.c */

  if(!bio_view_allowed(&user,target_username, course, &conf))  /* shared_bio.c */
      send_no_photo_image();
  else
    if(!photo_sent (course,  &conf,  target_username))
       send_no_photo_image();
  cs_cgi_destroy();
  return 0;			/* exit successfully */

}

