#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
              
#include "../global.h"

#include "shared_util.h"
#include "shared_cs_util.h"
#include "shared_file_util.h"

void
free_new_course_lock ()
{
  char lkfile[MAX_PATH + 1];

    snprintf (lkfile, MAX_PATH + 1, "%s%s", TMP_PATH, NEW_COURSE_LOCKFILE);
    unlink (lkfile);
}




void
get_new_course_lock()
{
#define STALE_SECS 300    /* a lock file older than this #seconds has been abandoned */

  char lkfile[MAX_PATH + 1];
  int i;
  int fd;
  extern int errno;
  struct stat buf;
  time_t now;
  
  snprintf (lkfile, MAX_PATH + 1, "%s%s", TMP_PATH, NEW_COURSE_LOCKFILE);
					    
  /* check for an abandoned lock file
  ** if it exists, and was modified more than STALE_SECS ago,
  ** then the file is probably abandoned and can be deleted 
  */					    
  if(!stat(lkfile, &buf))   /* if the lockfile exists */
   { 
    now = time(NULL);
    if( (now - buf.st_mtime) >  STALE_SECS)
        unlink(lkfile);
   }
    
  /* now create the lock file */      
  for (i = 1; i <= MAX_LOCK_ATTEMPTS; i++)
    {
      fd = open (lkfile, O_WRONLY | O_CREAT | O_EXCL, 0644);
      if ((fd < 0) && (errno == EEXIST))
	sleep (3);
      else if (fd < 0)
           cs_critical_error (ERR_CANT_GET_NEW_COURSE_LOCK, "");
      else
	{
	  close (fd);
	  change_mkstemp_permission(lkfile);   /* shared_file_util.c */
	  return;
	}
    }
  cs_critical_error (ERR_CANT_GET_NEW_COURSE_LOCK, "");

#undef STALE_SECS
}

