#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <openssl/sha.h>

#include "utils/nt_std_t.h" 
#include "utils/base64.h"
#include "utils/crypt.h"
#include "utils/file.h"


BOOL nt_make_sha1_path(const char *base_path, 
			const char *org_name, char **outbufp)
{
	assert(base_path != NULL); 
	assert(outbufp != NULL); 

	char *ptr;
	int len1, len2, i, offset;

	len1 = strlen(base_path);
	len2 = SHA_DIGEST_LENGTH * 2 + 4;

	ptr = (char*)malloc(len1 + len2);
	if(ptr == NULL)
		return FALSE;
	
	*outbufp = ptr;
	
	strcpy(ptr, base_path);
	ptr += len1;
	
	if(!nt_make_sha1_string(org_name, ptr, len2)){
		free(*outbufp);
		return FALSE;
	}

	if(!nt_mkdir(base_path)){
		free(*outbufp);
		return FALSE;
	}
		
	offset = 1;
	for(i = SHA_DIGEST_LENGTH*2; i > 0; i--){
		if(i == 2)
			offset = 0;
		ptr[i+offset] = ptr[i-1];
	}
	ptr[0] = '/';
	ptr[3] = '\0';
	if(!nt_mkdir(*outbufp)){
		free(*outbufp);
		return FALSE;
	}
	ptr[3] = '/';


	return TRUE;
}

BOOL nt_mkdir(const char *path)
{
	assert(path != NULL);

	if(0 == mkdir(path,
		S_IRUSR | S_IWUSR | S_IXUSR | S_IROTH))
		return TRUE;
	
	if(errno != EEXIST)
		return FALSE;
	
	return TRUE;
}
