/*  ZBPv2 Archiver tool (v0.1).	*/
/*  September 9th, 2007.	*/
/*  ~ DG.Ward (aka: Zeii)	*/
/*				*/
/*  warddg1@tekotago.ac.nz	*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#define MAGIC	0x3250425A	/* The string ZBP2. */

/* Some aliases to make the code slightly more sociable. */
typedef int8_t*	    arch_strtab;
typedef uint8_t*    arch_filebuf;

typedef struct
{
    uint32_t	hdr_magic;	/* Stores 'ZBP2'. Used to verify the archive. */
    uint32_t	hdr_rsvd;	/* 4b reserved for Programmer use. */
    uint32_t	hdr_enttab_off;	/* Offset of the Entry table within the archive. */
    uint32_t	hdr_strtab_off;	/* Offset of the String table within the archive. */
} arch_hdr;

typedef struct
{
    uint32_t ent_stridx;	/* Start index of the file's name in the String table. */
    uint32_t ent_file_off;	/* Start location of the file, within the archive. */
    uint32_t ent_file_sz;	/* Size of the file in bytes. */
    uint16_t ent_l_ent;		/* ID of the entry's left child, 0xFFFF marks NULL.  */
    uint16_t ent_r_ent;		/* ID of the entry's right child, 0xFFFF marks NULL. */
} arch_ent;

int8_t	    *of_name	= 0;	/* Points to the output filename. */
uint16_t    if_cnt	= 0;	/* Used to count the number of input files. */
uint32_t    strtab_sz	= 0;	/* Size of the string table, in bytes. */
uint8_t	    verbose	= 0;	/* Whether the program is operating in VERBOSE mode or not. */

arch_hdr    archive_header;
arch_ent    *archive_entries = 0;

arch_strtab archive_string_table = 0;
uint32_t    archive_strtab_off	 = 0;	/* The current usable offset within the String table. */

uint8_t	    **archive_filebuffers = 0;

/* Interprete tool parameters and initialize program elements. */
uint8_t interprete_parameters(int32_t argc, int8_t *argv[]);

/* Buffer all files and correctly set the file's entry. */
uint8_t create_archive(int32_t argc, int8_t *argv[]);

/* Insert the entry identified by ENTIDX into the entry BST. */
void place_entry(uint16_t entidx);

/* Flush the archive to disk. */
uint8_t dump_archive(void);

/* Correctly initialize the Archive's header. */
void setup_header(void)
{
    archive_header.hdr_magic = MAGIC;
    archive_header.hdr_rsvd = 0x00000000;

    archive_header.hdr_enttab_off = sizeof(arch_hdr) +
	(archive_entries[if_cnt - 1].ent_file_off + archive_entries[if_cnt - 1].ent_file_sz);

    archive_header.hdr_strtab_off = 
	archive_header.hdr_enttab_off + (if_cnt * sizeof(arch_ent));

    if(verbose)
    {
	printf(" > dataspace @ 0x%X\r\n", sizeof(arch_hdr));
	printf(" > enttab    @ 0x%X\r\n", archive_header.hdr_enttab_off);
	printf(" > strtab    @ 0x%X\r\n", archive_header.hdr_strtab_off);
	printf(" > arch_sz   = %d kByte(s).\r\n", (archive_header.hdr_strtab_off + strtab_sz) >> 10);
    }
}

/* Used for debugging, displays basic information about the file. */
void show_file_info(uint16_t entidx)
{
    printf("Entry #%d:\r\n", entidx);
    printf(" > Identifier: %s\r\n", &archive_string_table[archive_entries[entidx].ent_stridx]);
    printf(" > Located at 0x%X\r\n", archive_entries[entidx].ent_file_off);
    printf(" > Is %d byte(s) in size.\r\n", archive_entries[entidx].ent_file_sz);
}

/* Deallocation routine, releases all assets. */
void clean_up(void)
{
    /* Deallocate all dynamically allocated resources ... */
    if(archive_entries)	
	free(archive_entries);

    if(archive_string_table) 
	free(archive_string_table);

    if(archive_filebuffers) 
    {
	/* Release all buffers, within the buffer array ... */
	uint16_t chk_buf;
	for(chk_buf = 0; chk_buf < if_cnt; chk_buf++)
	{
	    if(archive_filebuffers[chk_buf])
	    {
		free(archive_filebuffers[chk_buf]);
		archive_filebuffers[chk_buf] = 0;
	    }
	}

	/* Then destroy the array itself... */
	free(archive_filebuffers);
    }
}

/* The core routine of the tool, it's fairly obvious. */
int32_t main(int argc, char *argv[])
{
    if(interprete_parameters(argc, (int8_t **)argv))
    {
    	clean_up();
	return -1;
    }

    if(create_archive(argc, (int8_t **)argv))
    {
    	clean_up();
	return -1;
    }
    else
    {
	/* Sort all entries, in alphabetical order ... */
	uint16_t sort_ent;
	for(sort_ent = 1; sort_ent < if_cnt; sort_ent++)
	    place_entry(sort_ent);

	setup_header();
	if(dump_archive())
	{
	    if(verbose) printf(" > Error writing archive to %s\r\n", of_name);
	    clean_up();
	    return -1;
	}
    }

    clean_up();
    return 0;
}

uint8_t interprete_parameters(int32_t argc, int8_t *argv[])
{
    /* prog -of= bla if= dir:file@path */
    if(argc < 5) return 1;
    else
    {
	uint32_t param_cnt;

	int8_t *if_path = 0;
	
	FILE *if_validate = 0;

	/* The responsibility of this loop is to:
	   a: set the output archive's name.
	   b: validate that the input files actually exist.
	   c: if the file does exist, it is a valid entry. */
	for(param_cnt = 1; param_cnt < (uint32_t)argc; param_cnt++)
	{
	    /* Does the user want verbose output? (-v) */
	    if(!strcmp("-v", (char *)argv[param_cnt])) verbose = 1;

	    /* Has a output target been specified? (-of=) */
	    if(!strcmp("-of=", (char *)argv[param_cnt]) && ((param_cnt + 1) < (uint32_t)argc))
		of_name = argv[param_cnt + 1];

	    /* Is at least one valid file being inserted into the archive? */
	    if(!strcmp("-if=", (char *)argv[param_cnt]) && ((param_cnt + 1) < (uint32_t)argc))
	    {
		if_path = argv[param_cnt + 1];
		while(*if_path++ != '@') strtab_sz++;	
		strtab_sz++;

		if((if_validate = fopen((char *)if_path, "rb")) == 0)
		{
		    if(verbose) printf("File %s doesn't exist.\r\n", if_path); 
		    if_validate = 0;
		    return 1;
		}
		
		fclose(if_validate);
		if_validate = 0;
		if_cnt++;
	    }
	}

	/* Ensure that the user hasn't tried to trick the program.
           The program *must* have an output path and at least one input file.
           If these conditions are not met, then the archive will not be created. */	
	if(!of_name || !if_cnt) return 1;
	else
	{
	    /* Now that the program knows exactly how many files are actually going
	       to be inserted into the resulting archive, it can create all needed
               tracking entries and file buffers. */
	    if(!(archive_entries = (arch_ent *)malloc(sizeof(arch_ent) * if_cnt)))
	    {
		if(verbose) printf("Failure allocating %d arch_ent(s).\r\n", if_cnt);
		return 1;
	    }
	    else if(!(archive_filebuffers = (uint8_t **)malloc(sizeof(uint8_t **) * if_cnt)))
	    {
		if(verbose) printf("Failure allocating %d arch_filebuf(s).\r\n", if_cnt);
		return 1;
	    }
	    else if(!(archive_string_table = (arch_strtab)malloc(sizeof(int8_t) * strtab_sz)))
	    {
		if(verbose) printf("Failure allocating space required for string table.\r\n");
		return 1;
	    }
	
	    /* Iniitalize all characters in our string table, to NULL. */
	    memset(archive_string_table, 0x00, (sizeof(int8_t) * strtab_sz));

	    /* If the program made it this far, we have now created all needed entries
               as well as the filebuffer array. Now, it's time to initialize them. */
	    for(param_cnt = 0; param_cnt < if_cnt; param_cnt++)
	    {
		archive_entries[param_cnt].ent_stridx	    = 
		    archive_entries[param_cnt].ent_file_off =
		    archive_entries[param_cnt].ent_file_sz  = 0;

		/* Maximum of $FFFE files within a single archive.
		   The program uses 0xFFFF as a terminator. */ 
		archive_entries[param_cnt].ent_l_ent	    =
		    archive_entries[param_cnt].ent_r_ent    = 0xFFFF;

		archive_filebuffers[param_cnt] = 0;
	    }
	}
    }

    /* Return success. */
    return 0;
}

/* The purpose of this routine is simply to buffer all input files
   and configure their entrie's correctly. */
uint8_t create_archive(int32_t argc, int8_t *argv[])
{
    uint32_t param_iter;
    uint16_t cur_ent = 0;

    FILE *if_in; 
    int8_t *strtab_ptr, *if_name, *if_path;

    for(param_iter = 1; param_iter < (uint32_t)argc; param_iter++)
    {
	if(!strcmp("-if=", (char *)argv[param_iter]))
	{
	    /* Retrieve the file's path and in-archive name. */
	    if_name = if_path = argv[param_iter + 1];
	    while(*if_path++ != '@');
	    *--if_path = 0x00;

	    /* Insert the file's in-archive name into the string table. */
	    strtab_ptr = &archive_string_table[archive_strtab_off];
	    strcpy((char *)strtab_ptr, (char *)if_name);

	    /* Update the entry's filename string index. */
	    archive_entries[cur_ent].ent_stridx = archive_strtab_off;

	    /* Update the strtab offset to point to the next free storage chunk! */
	    archive_strtab_off += (strlen((char *)if_name) + 1);

	    /* Begin loading the file's data ... */
	    if_in = fopen((char *)++if_path, "rb");
	    fseek(if_in, 0, SEEK_END);
	    archive_entries[cur_ent].ent_file_sz = ftell(if_in);

	    if(verbose) printf(" - %s ... ", if_name);

	    /* Attempt to allocate an appropriately sized buffer for the file's data. */
	    if(!(archive_filebuffers[cur_ent] = (uint8_t *)malloc(sizeof(uint8_t) * ftell(if_in))))
	    {
		if(verbose)
		{
		    printf("FAIL!\r\n");
		    printf(" > Couldn't allocate file buffer.\r\n");
		}	
		/* And hey, don't forget to release the file descriptor ... */
		fclose(if_in);
		return 1;
	    }

	    /* If that worked, initialize the space and buffer the file. */
	    memset(archive_filebuffers[cur_ent], 0x00, ftell(if_in));
	    fseek(if_in, 0, SEEK_SET);
	    fread(archive_filebuffers[cur_ent], archive_entries[cur_ent].ent_file_sz, 1, if_in);
	    fclose(if_in);

	    /* Set the file's offset within the archive */
	    if(cur_ent)	
	    {	
		archive_entries[cur_ent].ent_file_off +=
		    (archive_entries[cur_ent - 1].ent_file_off + archive_entries[cur_ent - 1].ent_file_sz); 
	    }

	    if(verbose) printf("OK!\r\n");
	    cur_ent++;
	}
    }

    return 0;
}

void place_entry(uint16_t entidx)
{
    uint16_t cmp_entidx = 0;
    int8_t *if_name = &archive_string_table[archive_entries[entidx].ent_stridx], *cmp_name;

    while((cmp_entidx < if_cnt) && (cmp_entidx < 0xFFFF))
    {
	if(cmp_entidx != entidx)
	{
	    cmp_name = &archive_string_table[archive_entries[cmp_entidx].ent_stridx];

	    if(strcmp((char *)if_name, (char *)cmp_name) < 0)
	    {
		if(archive_entries[cmp_entidx].ent_l_ent == 0xFFFF)
		    archive_entries[cmp_entidx].ent_l_ent = entidx, cmp_entidx = 0xFFFF;
		else cmp_entidx = archive_entries[cmp_entidx].ent_l_ent;
	    }
	    else
	    {
		if(archive_entries[cmp_entidx].ent_r_ent == 0xFFFF)
		    archive_entries[cmp_entidx].ent_r_ent = entidx, cmp_entidx = 0xFFFF;
		else cmp_entidx = archive_entries[cmp_entidx].ent_r_ent;
	    }
	}
    }
}

uint8_t dump_archive(void)
{
    FILE *of_out = fopen((char *)of_name, "wb");
    uint16_t buf_cnt;

    if(!of_out) return 1;
   
    fwrite(&archive_header, sizeof(arch_hdr), 1, of_out);

    for(buf_cnt = 0; buf_cnt < if_cnt; buf_cnt++)
	fwrite(archive_filebuffers[buf_cnt], archive_entries[buf_cnt].ent_file_sz, 1, of_out);

    fwrite(archive_entries, (sizeof(arch_ent) * if_cnt), 1, of_out);
    fwrite(archive_string_table, strtab_sz, 1, of_out);

    fclose(of_out);
    return 0; 
}
