/* user_install.c
// Perform the default installation steps
// Copyright Dec 1, 2002, Robin.Rowe@MovieEditor.com
// License MIT (http://opensource.org/licenses/mit-license.php)

#  Perform the default installation steps for the
#  specified user home directory:
#
#  1) Create ~/.filmgimp if it doesn't exist
#  2) Copy system gimprc file to ~/.filmgimp
#  3) Create brushes, gradients, palettes, patterns, plug-ins subdirs
#  4) Create the tmp subdirectory for disk-swapping undo buffers
#  5) Copy the palette files in system palette directory
#  6) Copy the vbr brush files in system vbr to ~/.filmgimp/brushes directory
#  */

//#include <gwin32.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "../lib/wire/datadir.h"
#include "user_install.h"

#define MKDIR(dir) \
	name=dir;\
	strcpy(buffer+len,name);\
	status=mkdir(buffer,0777);\
	if(-1==status && EEXIST!=errno)\
		return name

int CopyFile(const char *from_name,const char *to_name)
{	enum {buf_size=512};
	char buffer[buf_size];
	int in=open(from_name,O_RDONLY);
	int out=open(to_name,O_CREAT|O_WRONLY|S_IWRITE, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
	int bytes=0;
	int totalNBytes = 0;
	while(1)
        {	bytes=read(in,buffer,buf_size);
		if(0>=bytes)
		{	break;
		}	
        	int nWrite = write(out,buffer,bytes);//bug
		if(nWrite != bytes) {
		   totalNBytes = 0;
		   break;
		}
		totalNBytes += nWrite;
	}
	close(in);
	close(out);
	return (0==bytes);
}
	
/* returns error message or 0 */
const char* UserInstall(const char* gimpdir)
{	enum {MAXPATHLEN=255};
	char buffer[MAXPATHLEN];
	size_t len=0;
	int status;
	const char* name;
	const char* homedir=GetDirHome();
	MKDIR(homedir);
	MKDIR(gimpdir);
	puts(gimpdir);
	len=strlen(gimpdir);
	strcpy(buffer,gimpdir);
	name="/cinepaintrc";
	strcpy(buffer+len,name);
	if(!CopyFile("cinepaintrc",buffer))
	{	return buffer;
	}
	name="/gtkrc";
	strcpy(buffer+len,name);
	if(!CopyFile(name+1,buffer))
	{	return buffer;
	}
//	len=strlen(homedir);
//	strcpy(buffer,homedir);
	MKDIR("/brushes");
	MKDIR("/gradients");
	MKDIR("/palettes");
	MKDIR("/patterns");
	MKDIR("/plug-ins");
	MKDIR("/gfig");
	MKDIR("/tmp");
	MKDIR("/scripts");
	MKDIR("/gflares");
	return 0;
}
