#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#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_file_util.h"



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




static void
send_tar (const char *course, const char *tar_path)
{
    char *slash;
    FILE *fp;
    struct stat buf;
    char *buffer;

    slash = strchr(course, '/');
    if(!slash)
	cs_critical_error(ERR_TAR_PATH_ERROR, course);
    slash++;

    if(stat(tar_path, &buf))
	    cs_critical_error (ERR_STAT_FAILED, tar_path);
    buffer = (char *) malloc( (buf.st_size +1) * sizeof(char));
    if(!buffer)
         cs_critical_error (ERR_MALLOC_FAILED, "");

    fp = fopen(tar_path, "r");
    if(!fp)
       cs_critical_error(ERR_FOPEN_READ_FAILED, tar_path);
    if (fread (buffer, buf.st_size, 1, fp) != 1)
       cs_critical_error (ERR_FREAD_FAILED, tar_path);
    fclose(fp);
    printf ("Content-type:application/octet-stream\n");
    printf ("Content-disposition:attachment; filename=\"%s.tar.gz\"\n\n", slash);
    if(fwrite(buffer, buf.st_size, 1, stdout) != 1)
	    cs_critical_error (ERR_FWRITE_FAILED, tar_path);
    free(buffer); 
}




void
tar_courses(const char *course, char *tar_path)
{
    char subdir_path[MAX_PATH +1];
    char course_dir[MAX_PATH +1];
    char cmd[MAX_PATH*2 +1];
    char *slash;
    int fd;

    snprintf(tar_path, MAX_PATH +1,"%sCGI_DATA_tar_XXXXXX", TMP_PATH);
    fd = mkstemp(tar_path);
    if(fd == -1)
        cs_critical_error (ERR_MKSTEMP_FAILED, tar_path);
      close(fd);
   change_mkstemp_permission(tar_path);   /*shared_file_util.c */
    slash = strchr(course, '/');
    if(slash)
      *slash = '\0';
    snprintf(subdir_path, MAX_PATH +1, "%s%s", *(course) == 'T' ? TEMPLATE_PATH:COURSE_PATH, course);
    *slash = '/';
    slash++;
    snprintf(course_dir, MAX_PATH +1, "%s", slash);
    snprintf(cmd, MAX_PATH *2 +1, "cd %s; tar -czf %s.tar.gz %s; mv %s.tar.gz ../%s; cd ../../sbin", 
       subdir_path, course_dir, course_dir, course_dir,  tar_path);
    system(cmd);
}

int
main ()
{
  char course[MAX_PATH + 1];	/* from crs=? command line */
  char key[MAX_KEY + 1];	/* from id=? command line */
  char tar_path[MAX_PATH + 1];	/* from id=? command line */
  SESSION user;
  cs_cgi_init();
  read_parameters ( key, course);
  validate_super_key(key, &user);    /* shared_super_util.c */
  tar_courses(course, tar_path);
  send_tar (course, tar_path );
  unlink(tar_path);
  cs_cgi_destroy();
  return 0;			/* exit successfully */

}
