#include <stdio.h>
#include <stdlib.h>
#include "global.h"
#include "custom.h"
#include <string.h>
#include <dirent.h>             /* Directory information. */
#include <sys/stat.h>           /* for stat()            */
#include <sys/file.h>           /* flock() */




#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_super_util.h"
#include "manhat-lib/shared_authenticate.h"
#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_news_util.h"
#include "manhat-lib/shared_lock.h"
#include "manhat-lib/shared_file_util.h"
#include "manhat-lib/shared_time.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_super_menu.h"

void
re_write_index(const char *del_username, ADMIN_USER *list)
{
     FILE *fp;
     char fname[MAX_PATH +1];
     ADMIN_USER *ptr;

     snprintf(fname, MAX_PATH +1, "../%s/%s/%s", USERS_DIR, ADMIN_DIR, USER_INDEX_FNAME);
     fp = fopen(fname, "w");
     if(!fp)
       cs_critical_error( ERR_FOPEN_WRITE_FAILED, "");
     get_exclusive_lock(fileno(fp), 1);
     for(ptr = list; ptr; ptr = ptr->next)
       if(strcmp(ptr->username, del_username)!=0)	     
          fprintf(fp, "%s:%s\n", ptr->username, ptr->realname);
     release_lock(fileno(fp));
     fclose(fp);
}

void
read_parameters( char *key, char *del_name)
{
     cs_get_required_parameter("id", key,  MAX_KEY);
     cs_get_required_parameter("list_user", del_name, MAX_USERNAME + MAX_NAME +1);
}


void
set_data(  char *del_username,  char *del_realname)
{

    cs_set_current_time();	
    cs_set_value("del_username", del_username);
    cs_set_value("del_realname", del_realname);
    cs_set_int_value("del_success", 1);
}



void
do_action( const char *key,
		 char *del_name)
{
	char *ptr;
        char del_user_dir[MAX_PATH +1];
	ADMIN_USER *list;

	ptr = strchr(del_name, ':');
	*ptr = '\0';
	ptr++;
        if(strlen(del_name) >4)
	{
	  snprintf(del_user_dir, MAX_PATH +1, "../%s/%s/%c/%s",
		 USERS_DIR,  ADMIN_DIR, sub_dir_name(del_name), del_name);
	  list = build_admin_user_list(); /*shared_super_util.c */
	  kill_directory(del_user_dir); /* shared_file_util.c */
	  re_write_index(del_name, list);
	  free_admin_user_list(list);    /* shared_super_util.c */
          set_data(  del_name,  ptr);
	}
	else
         cs_critical_error(ERR_PARAM_MISSING, "user_list");
	
}


     
		    
int
main()
{
    char key[MAX_KEY +1];
    char del_name[MAX_USERNAME + MAX_NAME +2];
    SESSION user;
   
    cs_cgi_init(); 
    read_parameters( key, del_name);
    validate_super_key(key, &user);
    set_admin_page(&user, key, 0, "super_del_admin_form");  /* shared_super_menu.c */
    
    do_action( key, del_name);
    cs_cgi_display("super_del_admin_form", 1);
    cs_cgi_destroy(); 
    return 0;
}
    

    

