#include <xvfs-core.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <tcl.h>

#define XVFS_NAME_LOOKUP_ERROR (-1)
#define XVFS_FILE_BLOCKSIZE 1024

/*
 * XXX:TODO: Determine this automatically rather than
 *           by heuristics
 */
#define HAVE_STRUCT_STAT_ST_BLKSIZE 1
#define HAVE_STRUCT_STAT_ST_BLOCKS  1
#ifdef WIN32
#  undef HAVE_STRUCT_STAT_ST_BLKSIZE
#  undef HAVE_STRUCT_STAT_ST_BLOCKS
#endif

#define MIN(a, b) (((a) < (b)) ? (a) : (b))

typedef enum {
	XVFS_FILE_TYPE_REG,
	XVFS_FILE_TYPE_DIR
} xvfs_file_type_t;

typedef Tcl_WideInt xvfs_size_t;

struct xvfs_file_data {
	const char          *name;
	xvfs_file_type_t    type;
	xvfs_size_t         size;
	union {
		const unsigned char *fileContents;
		const char          **dirChildren;
	} data;
};

<?
	package require xvfs

	set ::xvfs::hashNameThreshold 3
	if {[info exists ::env(XVFS_CREATE_HASH_NAME_THRESHOLD)]} {
		set ::xvfs::hashNameThreshold $::env(XVFS_CREATE_HASH_NAME_THRESHOLD)
	}
	if {$::xvfs::hashNameThreshold < 0} {
		set ::xvfs::hashNameThreshold [expr {2**31}]
	}
	xvfs::main $::xvfs::argv

	proc emitFilenameVerification {indentLevel outputFileNameLen outputFileIndexes} {
		set indent [string repeat "\t" $indentLevel]
		foreach outputFileIndex $outputFileIndexes {
?><?= $indent ?>if (memcmp(path, xvfs_<?= $::xvfs::fsName ?>_data[<?= $outputFileIndex ?>].name, <?= $outputFileNameLen ?>) == 0) {
<?= $indent ?>	return(<?= $outputFileIndex ?>);
<?= $indent ?>}
<?
		}
	}
?>
static long xvfs_<?= $::xvfs::fsName ?>_nameToIndex(const char *path) {
<?
	for {set index 0} {$index < [llength $::xvfs::outputFiles]} {incr index} {
		set outputFileName [lindex $::xvfs::outputFiles $index]
		set outputFileNameLen [string length $outputFileName]
		set outputFileNameHash [zlib adler32 $outputFileName 0]
		lappend outputFileNameHashToIndex([list $outputFileNameLen $outputFileNameHash]) $index
		lappend outputFileNameLenToIndex($outputFileNameLen) $index
	}

	set needZlib false
	foreach {outputFileNameLen outputFileIndexes} [lsort -stride 2 -dictionary [array get outputFileNameLenToIndex]] {
		if {[llength $outputFileIndexes] > $::xvfs::hashNameThreshold} {
			set needZlib true
			break;
		}
	}
?><?
	if {$needZlib} {
?>	unsigned int pathHash;
<?	} ?>	size_t pathLen;
	
	if (path == NULL) {
		return(XVFS_NAME_LOOKUP_ERROR);
	}

	pathLen = strlen(path);
	switch (pathLen) {
<?

	foreach {outputFileNameLen outputFileIndexes} [lsort -stride 2 -dictionary [array get outputFileNameLenToIndex]] {
?>		case <?= $outputFileNameLen ?>:
<?
			if {[llength $outputFileIndexes] > $::xvfs::hashNameThreshold} {
?>			pathHash = Tcl_ZlibAdler32(0, (const unsigned char *) path, <?= $outputFileNameLen ?>);
			switch (pathHash) {
<?
				foreach {key outputFileIndexes} [lsort -stride 2 -dictionary [array get outputFileNameHashToIndex [list $outputFileNameLen *]]] {
					set outputFileNameHash [lindex $key 1]
?>				case <?= $outputFileNameHash ?>:
<?
					emitFilenameVerification 5 $outputFileNameLen $outputFileIndexes
?>					break;	
<?
				}
?>			}
<?
			} else {
				emitFilenameVerification 3 $outputFileNameLen $outputFileIndexes
			}
?>			break;
<?	} ?>	}
	
	return(XVFS_NAME_LOOKUP_ERROR);
}

static const char **xvfs_<?= $::xvfs::fsName ?>_getChildren(const char *path, Tcl_WideInt *count) {
	const struct xvfs_file_data *fileInfo;
	long inode;

	/*
	 * Validate input parameters
	 */
	if (count == NULL) {
		return(NULL);
	}
	
	/*
	 * Get the inode from the lookup function
	 */
	inode = xvfs_<?= $::xvfs::fsName ?>_nameToIndex(path);
	if (inode == XVFS_NAME_LOOKUP_ERROR) {
		*count = XVFS_RV_ERR_ENOENT;
		return(NULL);
	}
	
	fileInfo = &xvfs_<?= $::xvfs::fsName ?>_data[inode];

	/*
	 * Ensure this is a directory
	 */
	if (fileInfo->type != XVFS_FILE_TYPE_DIR) {
		*count = XVFS_RV_ERR_ENOTDIR;
		return(NULL);
	}
	
	*count = fileInfo->size;
	return(fileInfo->data.dirChildren);
}

static const unsigned char *xvfs_<?= $::xvfs::fsName ?>_getData(const char *path, Tcl_WideInt start, Tcl_WideInt *length) {
	const struct xvfs_file_data *fileInfo;
	Tcl_WideInt resultLength;
	long inode;

	/*
	 * Validate input parameters
	 */
	if (length == NULL) {
		return(NULL);
	}
	
	if (start < 0) {
		*length = XVFS_RV_ERR_EINVAL;
		return(NULL);
	}
	
	if (*length < 0) {
		*length = XVFS_RV_ERR_EINVAL;
		return(NULL);
	}
	
	/*
	 * Get the inode from the lookup function
	 */
	inode = xvfs_<?= $::xvfs::fsName ?>_nameToIndex(path);
	if (inode == XVFS_NAME_LOOKUP_ERROR) {
		*length = XVFS_RV_ERR_ENOENT;
		return(NULL);
	}
	
	fileInfo = &xvfs_<?= $::xvfs::fsName ?>_data[inode];

	/*
	 * Ensure this is a file that can be read
	 */
	if (fileInfo->type != XVFS_FILE_TYPE_REG) {
		*length = XVFS_RV_ERR_EISDIR;
		return(NULL);
	}

	/*
	 * Validate the length
	 */
	if (start > fileInfo->size) {
		*length = XVFS_RV_ERR_EFAULT;
		return(NULL);
	}

	if (*length == 0) {
		resultLength = fileInfo->size - start;
	} else {
		resultLength = MIN(fileInfo->size - start, *length);
	}
	*length = resultLength;

	/*
	 * Return the data
	 */
	return(fileInfo->data.fileContents + start);
}

static int xvfs_<?= $::xvfs::fsName ?>_getStat(const char *path, Tcl_StatBuf *statBuf) {
	const struct xvfs_file_data *fileInfo;
	long inode;

	/*
	 * Validate input parameters
	 */
	if (!statBuf) {
		return(XVFS_RV_ERR_EINVAL);
	}
	
	/*
	 * Get the inode from the lookup function
	 */
	inode = xvfs_<?= $::xvfs::fsName ?>_nameToIndex(path);
	if (inode == XVFS_NAME_LOOKUP_ERROR) {
		return(XVFS_RV_ERR_ENOENT);
	}
	
	fileInfo = &xvfs_<?= $::xvfs::fsName ?>_data[inode];
	
	statBuf->st_dev   = <?= [zlib adler32 $::xvfs::fsName] ?>;
	statBuf->st_rdev  = <?= [zlib adler32 $::xvfs::fsName] ?>;
	statBuf->st_ino   = inode;
	statBuf->st_uid   = 0;
	statBuf->st_gid   = 0;
	statBuf->st_atime = 0;
	statBuf->st_ctime = 0;
	statBuf->st_mtime = 0;
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
	statBuf->st_blksize = XVFS_FILE_BLOCKSIZE;
#endif
	
	if (fileInfo->type == XVFS_FILE_TYPE_REG) {
		statBuf->st_mode   = 0100444;
		statBuf->st_nlink  = 1;
		statBuf->st_size   = fileInfo->size;
#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
		statBuf->st_blocks = (fileInfo->size + statBuf->st_blksize - 1) / statBuf->st_blksize;
#endif
	} else if (fileInfo->type == XVFS_FILE_TYPE_DIR) {
		statBuf->st_mode   = 040555;
		statBuf->st_nlink  = fileInfo->size;
		statBuf->st_size   = fileInfo->size;
#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
		statBuf->st_blocks = 1;
#endif
	}
	
	return(0);
}

static struct Xvfs_FSInfo xvfs_<?= $::xvfs::fsName ?>_fsInfo = {
	.protocolVersion = XVFS_PROTOCOL_VERSION,
	.name            = "<?= $::xvfs::fsName ?>",
	.getChildrenProc = xvfs_<?= $::xvfs::fsName ?>_getChildren,
	.getDataProc     = xvfs_<?= $::xvfs::fsName ?>_getData,
	.getStatProc     = xvfs_<?= $::xvfs::fsName ?>_getStat
};

int Xvfs_<?= $::xvfs::fsName ?>_Init(Tcl_Interp *interp) {
	int register_ret;

#ifdef USE_TCL_STUBS
	const char *tclInitStubs_ret;
	/* Initialize Stubs */
	tclInitStubs_ret = Tcl_InitStubs(interp, TCL_PATCH_LEVEL, 0);
	if (!tclInitStubs_ret) {
		return(TCL_ERROR);
	}
#endif
	
	register_ret = Xvfs_Register(interp, &xvfs_<?= $::xvfs::fsName ?>_fsInfo);
	if (register_ret != TCL_OK) {
		return(register_ret);
	}
	
	return(TCL_OK);
}
#undef XVFS_NAME_LOOKUP_ERROR
#undef XVFS_FILE_BLOCKSIZE
