#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

#include "global.h"
#include "custom.h"		/* for date FORMAT strings */

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_file_util.h"

void
read_parameters (char *course, char *key)
{


  cs_get_required_parameter ("crs", course, MAX_PATH);
  cs_get_required_parameter ("id", key, MAX_KEY);

}

static void
show_disk_stats (CONFIG_STRUCT *conf, SESSION *user)
{
  #define MAX_TMP_NAME 30
  int fd;
  char template[MAX_PATH + 1];
  char temp_path[MAX_PATH + 1];
  char cmd[MAX_PATH * 2];
  FILE *fp;
  char line[200];
  char *ptr;
  char name[MAX_TMP_NAME];
  int i =0;

  cs_set_course_info(conf);
  cs_set_current_time();
  
  snprintf (template, MAX_PATH + 1, "%sCGI_DATA_%s_dsk_XXXXXX", TMP_PATH,
	    user->username);
  fd = mkstemp(template);
  if(fd == -1)
     cs_critical_error(ERR_MKSTEMP_FAILED,"");
  close(fd);
  change_mkstemp_permission(template);   /* shared_file_util.c */
  strncpy (temp_path, template, MAX_PATH + 1);

  snprintf (cmd, MAX_PATH * 2, "du -s %s > %s", conf->course_path, temp_path);
  system (cmd);


  snprintf (cmd, MAX_PATH * 2, "df -h . >> %s", temp_path);
  system (cmd);

  fp = fopen (temp_path, "r");
  if (!fp)
    {
      unlink (temp_path);
      cs_critical_error (ERR_FOPEN_READ_FAILED, temp_path);
    }

  if (!fgets (line, 199, fp))
    cs_critical_error (ERR_FREAD_FAILED, temp_path);
  for (ptr = line; *ptr && !isspace (*ptr); ptr++);
  *ptr = '\0';
  snprintf(name, MAX_TMP_NAME, "disk.kilobytes");
  cs_set_value(name, line);
  while (fgets (line, 199, fp))
  {
    snprintf(name, MAX_TMP_NAME, "disk.line.%d", i);
    cs_set_value(name,line);
    i++;
  }
  fclose (fp);
  unlink (temp_path);

}



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;

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


  if ( (user.group == FACULTY) || (user.group == ADMIN))
    show_disk_stats (&conf, &user);
  else
    cs_critical_error (ERR_REQUEST_DENIED, "");
  cs_cgi_display("stats_disk", 1);
  cs_cgi_destroy();
  return 0;			/* exit successfully */

}

