/* Copyright 2013 Akira Ohta (akohta001@gmail.com)
    This file is part of ntch.

    The ntch is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    The ntch is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ntch.  If not, see <http://www.gnu.org/licenses/>.
    
*/
#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 <wchar.h>

#include "utils/nt_std_t.h" 
#include "utils/base64.h"
#include "utils/crypt.h"
#include "utils/file.h"
#include "utils/text.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;
}

nt_link_tp nt_read_text_file(const char* path)
{
	nt_link_tp linkp, wrkp;
	FILE *fp;
	wchar_t wc[256];
	wchar_t *cptr;
	
	linkp = NULL;
	
	fp = fopen(path, "r");
	if(!fp)
		return NULL;
	
	while(fgetws(wc, sizeof(wc)/sizeof(wchar_t)-1, fp)){
		cptr = nt_w_trim(wc);
		if(cptr){
			wrkp = nt_link_add_data(linkp, cptr);
			if(!linkp)
				linkp = wrkp;
		}
	}
	fclose(fp);
	return linkp;
}

BOOL nt_write_text_file(const char* path, nt_link_tp text)
{
	nt_link_tp linkp;
	FILE *fp;
	wchar_t *cptr;
	
	linkp = NULL;
	
	fp = fopen(path, "w");
	if(!fp)
		return FALSE;
	
	linkp = text;
	do{
		cptr = linkp->data;
		if(-1 == fputws(cptr, fp)){
			goto ERROR_TRAP;
		}
		if(-1 == fputws(L"\n", fp)){
			goto ERROR_TRAP;
		}
		linkp = linkp->next;
	}while(linkp != text);
	
	fclose(fp);
	return TRUE;
ERROR_TRAP:
	fclose(fp);
	return FALSE;
}
