#include <stdio.h>
#include <string.h>
#include <dirent.h>		/* Directory information. */

#include <sys/stat.h>		/* for stat()            */
#include <sys/file.h>		/* for flock()            */
#include <unistd.h>		/* for unlink, mktmp ... */

#include <time.h>

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

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_super_util.h"
#include "manhat-lib/shared_authenticate.h"
#include "manhat-lib/shared_lock.h"
#include "manhat-lib/shared_strtrm.h"
#include "manhat-lib/shared_file_util.h"
#include "manhat-lib/shared_cookie.h"
#include "manhat-lib/shared_encrypt.h"
#include "manhat-lib/shared_central_log.h"

#include "manhat-lib/shared_cs_util.h"	/* for get_string_value() */






static void
read_parameters ( char *username, char *password, int *first)
{

  cs_get_required_parameter("username", username, MAX_USERNAME);
  cs_get_required_parameter("password", password, MAX_PASSWORD);
  //cs_get_required_parameter("first", temp, 9);
  *first = 1;
}









void
check_super_password (const char *username, const char *plaintext_password)
{
   char correct_password[MAX_ENCRYPTED_PASSWORD + 1];
   int username_ok;
   
   username_ok = get_super_user_password(username, correct_password);   /* shared_encrypt.c */
   
   if(!username_ok)
       cs_critical_error (ERR_USERNAME_PASSWD_INCORRECT, "");
   
   if(!strlen(correct_password) ||
            strcmp(correct_password, encrypted_password(plaintext_password, username)))  /* shared_encrypt.c */
       {
          write_central_log(username,hdf_get_value(global_cgi->hdf, "log_event.wrong_password", ""),"",1);     /* shared_central_log.c */         
          cs_critical_error (ERR_USERNAME_PASSWD_INCORRECT, "");
       }   
}



void
rotate_logfile()
{
   char logfile[MAX_PATH +1];
   char new_filepath[MAX_PATH +1];
   char new_filename[MAX_FILENAME + 1];
   struct stat buf;
   char ch;
   FILE *fp;


   snprintf(logfile, MAX_PATH +1, "%s/%s", LOG_PATH, LOG_FNAME);
   if(stat(logfile, &buf) ==0)  /* if file exists */
   {
      if(buf.st_size > MAX_LOGIN_LOG_SIZE)   /* custom.h */
      {
        /* new filename contains the modification time DDMonYYYY of the current log file */
        strftime(new_filename, MAX_FILENAME + 1, "log_%d%b%Y_%H%M", localtime(&buf.st_mtime));
        snprintf(new_filepath,MAX_PATH + 1, "%s/%s", LOG_PATH, new_filename);
        
        /** If for some strange reason, new_filepath already exists, add an 'A' to the
        *** end of the filename, then begin search for a unique name 
        **/
            if(file_exists(new_filepath))
              {
                strcat(new_filepath,"A");
                for(ch = 'B'; file_exists(new_filepath) && (ch <= 'Z'); ch++)
                           *(new_filepath + strlen(new_filepath) - 1) = ch;
                           
                if(ch > 'Z')
                    return;   /* we just won't rotate the log if we can't get a unique filename */           
              }               

                                
   	 rename(logfile,new_filepath);
   	 fp = fopen(logfile, "a");   /* create an empty logfile */
   	 if(fp)
   	    fclose(fp);
      }
      
   }
}










void
record_successful_login(const char *username)
{

     
     /* the login log file is rotated whenever an administrator logs into 
     ** the administrative system (if the size of the current file exceeds
     ** MAX_LOGFILE
     */
     rotate_logfile();    /* shared_rotate_log.c */
     

     write_central_log(username, hdf_get_value(global_cgi->hdf, "log_event.successful_login",""),"",1);   /* shared_central_log.c */
          
#undef MAX_LOGFILE     
}
     
     
     
static void
super_login(const char *username, const char *password,  int first)
{
 char key[MAX_KEY + 1];

 cs_set_event_msg();
 check_super_password (username, password);
 create_super_key(username,key);      /* shared_super_key.c */
 record_successful_login(username);
 if(SUPER_COOKIES_ENABLED) /* custom.h */
 {
   
    set_cookie(key, SBIN_ALIAS, "");    /* shared_cookie.c */
    printf("<html><head><meta http-equiv=\"REFRESH\" content=\"0; URL=%s?id=%s&first=%d\"></head></html>",
		                           "super_check_cookie", USE_COOKIE, first);

 }
 else
    printf("Location:%s?id=%s&first=%d\n\n", "super_admin_page",  key, first);
}


int
main ()
{

  char username[MAX_USERNAME + 1];
  char password[MAX_PASSWORD + 1];
  int first;

  cs_cgi_init();
  read_parameters ( username, password, &first);
  super_login(username, password,  first);
  cs_cgi_destroy();
  return 0;
}

