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

#include "../global.h"

#include "shared_cs_util.h"
#include "shared_lock.h"
#include "shared_authenticate.h"


void
mark_passwd_file (const char *username, const CONFIG_STRUCT *conf)
{
  FILE *fp;
  int fd;
  int found = 0;
  long offset = 0;
  char line[200];
  char *ptr;
  char qmark = '?';
  char passwd_fname[MAX_PATH + 1];

  snprintf (passwd_fname, MAX_PATH + 1, "%s%s", conf->course_path, PASSWD_FNAME);
  fp = fopen (passwd_fname, "r+");	/* open for reading and writing */
  
  if (!fp)
    cs_critical_error (ERR_PASSWD_OPEN_FAILED, "");
  fd = fileno(fp);
  get_exclusive_lock(fd, 1);                      /* shared_lock.c */

  while (!found && fgets (line, 199, fp))
    {
      if (*line != '?')		/* skip usernames that start with ? */
	{
	  ptr = strchr (line, ':');
	  if (!ptr)
	    cs_critical_error (ERR_PASSWD_PARSE_ERROR, "");
	  *ptr = '\0';
	  if (!strcmp (line, username))
	    {
	      fseek (fp, offset, SEEK_SET);
	      if (fwrite (&qmark, sizeof (char), 1, fp) != 1)
		cs_critical_error (ERR_FWRITE_FAILED, "");
	      found = 1;
	    }

	}
      offset = ftell (fp);
    }

  release_lock(fd);
  fclose (fp);
  if (!found)
    {
      cs_critical_error (ERR_NO_STUDENT_FOUND, username);
    }
}




void
update_passwd (const USER_DATA * new_info, const CONFIG_STRUCT *conf)
{
  FILE *fp;
  int fd;
  char passwd_fname[MAX_PATH + 1];


  snprintf (passwd_fname, MAX_PATH + 1, "%s%s", conf->course_path, PASSWD_FNAME);
  fp = fopen (passwd_fname, "a");
  if (!fp)
    cs_critical_error (ERR_FOPEN_APPEND_FAILED, "");
  fd = fileno(fp);
  get_exclusive_lock(fd, 1);                      /* shared_lock.c */
  
    fprintf (fp, "%s:x:%s:%s:%s:%c:%s\n",
	    new_info->username, new_info->realname,
	    (new_info->group== FACULTY) ? "faculty" : "student", new_info->alias, new_info->team, new_info->id);

  release_lock (fd);
  fclose (fp);
}




/* writes new realname, alias, team, to session key
** if it exists
**/
void
update_course_key(const USER_DATA *new_info, const char *course)
{
 char key_path[MAX_PATH + 1];
 FILE *fp;
 SESSION user;


 /* sub_dir_name() is in shared_authenticate.c */
 snprintf(key_path, MAX_PATH + 1, "../%s/%c/%s/%s%s", USERS_DIR, sub_dir_name(new_info->username), new_info->username,  
                                         course, KEY_FILE_EXTENSION);   
 fp = fopen(key_path, "r+");
 if(fp)
  {
   if(fread(&user, sizeof(SESSION), 1, fp) == 1)
    {
     snprintf(user.realname, MAX_NAME + 1, new_info->realname);
     snprintf(user.alias, MAX_NAME + 1, new_info->alias);
     user.team = new_info->team;
    
     if(!fseek(fp,0,SEEK_SET))
       fwrite(&user, sizeof(SESSION), 1, fp);
    }   
   fclose(fp);
  }
}  



