#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

              

#include "../global.h"

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





void
change_mkstemp_permission(const char *file)
{
 
 if(!chown(file, -1, getgid()))   /* change the group of the file to the group Apache is running as */
    chmod(file, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP );  /* change permission to rwxrwx--- */
    
 
}



int
file_exists (const char *path)
{
  struct stat buf;

  return !stat (path, &buf); 
}




		
int
isdirectory (const char *dirname, const char *fname)
{
  struct stat buf;
  char path[MAX_PATH + 1];

  snprintf (path, MAX_PATH + 1, "%s/%s", dirname, fname);

  stat (path, &buf);
  return S_ISDIR (buf.st_mode);
}




/* one of the few places Manhattan uses system()
** completely delete the directory named dirname
*/

void
kill_directory (const char *dirname)
{
#define RM_CMD "rm -Rf "

 struct stat buf;
 char *cmd;
 int size;
 
 if(!stat (dirname, &buf) && S_ISDIR(buf.st_mode))   /* if dirname exists, and it is a directory */
  {
   size = strlen(dirname) + strlen(RM_CMD) + 10;
   cmd = (char *)malloc(size + sizeof(char));
   if(!cmd)
      cs_critical_error(ERR_MALLOC_FAILED, "");
   snprintf(cmd,size, "%s \"%s\"",RM_CMD,dirname);
   system(cmd);
   free(cmd);
  }
}


int create_dirs_between(char *path)
{
     char temp[MAX_PATH +1];
     int i = 0, flag = -1, j;
     char stack[20][MAX_PATH +1];
     char *ptr;
   if(file_exists(path))
	 return 1;
     
    strncpy(temp, path, MAX_PATH +1);


    if(temp[strlen(temp) -1] == '/')
       temp[strlen(temp)-1] = '\0'; 

    do
    {
        if(mkdir (temp, 0777))
	{
            ptr = strrchr(temp, '/');
	    if(ptr)
	    {
	       *ptr = '\0';
	       ptr++;
               strncpy(stack[i], ptr, MAX_PATH +1);
	       i++;
	    }	
	}
	else
            flag = 1;

    }while(flag == -1); 
  
    if(i > 0)
    {
	for(j = i -1; j >=0; j--)
	{
	    strcat(temp, "/");
	    strcat(temp, stack[j]);
            if(mkdir (temp, 0777))
	    {
		  return 0;
	    }
	}
    }
   return 1; 
}

