/*

Copyright (c) 2011, 2012, Simon Howard

Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 */

#include "../../common.h"
#include "lhasa.h"
#include "lha_decoder.h"
#include "lha_basic_reader.h"
#include "macbinary.h"

typedef enum {

	// Initial state at start of stream:

	CURR_FILE_START,

	// Current file is a "normal" file (or directory) read from
	// the input stream.

	CURR_FILE_NORMAL,

	// Current file is a directory that has been popped from the
	// directory stack.

	CURR_FILE_FAKE_DIR,

	// Current file is a deferred symbolic link that has been left
	// to the end of the input stream to be created.

	CURR_FILE_DEFERRED_SYMLINK,

	// End of input stream has been reached.

	CURR_FILE_EOF,
} CurrFileType;

struct _LHAReader {
	LHABasicReader *reader;

	// The current file that we are processing (last file returned
	// by lha_reader_next_file).

	LHAFileHeader *curr_file;
	CurrFileType curr_file_type;

	// Pointer to decoder being used to decompress the current file,
	// or NULL if we have not yet started decompression.

	LHADecoder *decoder;

	// Pointer to "inner" decoder. Most of the time,
	// decoder == inner_decoder, but when decoding an archive
	// generated by MacLHA, inner_decoder points to the actual
	// decompressor.

	LHADecoder *inner_decoder;

	// Policy used to extract directories.

	LHAReaderDirPolicy dir_policy;

	// Directories that have been created by lha_reader_extract but
	// have not yet had their metadata set. This is a linked list
	// using the _next field in LHAFileHeader.
	// In the case of LHA_READER_DIR_END_OF_DIR this is a stack;
	// in the case of LHA_READER_DIR_END_OF_FILE it is a list.

	LHAFileHeader *dir_stack;

	// Symbolic links containing absolute paths or '..' are not
	// created immediately - instead, "placeholder" files are created
	// in their place, and the symbolic links created at the end
	// of extraction.

	LHAFileHeader *deferred_symlinks;
};

/**
 * Free the current decoder structure.
 *
 * If the reader has an allocated decoder being used to decompress the
 * current file, the decoder is freed and the decoder pointer reset
 * to NULL.
 *
 * @param reader         Pointer to the LHA reader structure.
 */

static void close_decoder(LHAReader *reader)
{
	if (reader->decoder != NULL) {
		if (reader->inner_decoder == reader->decoder) {
			reader->inner_decoder = NULL;
		}

		lha_decoder_free(reader->decoder);
		reader->decoder = NULL;
	}

	if (reader->inner_decoder != NULL) {
		lha_decoder_free(reader->inner_decoder);
		reader->inner_decoder = NULL;
	}
}

/**
 * Create the decoder structure to decompress the data from the
 * current file.
 *
 * @param reader         Pointer to the LHA reader structure.
 * @return               Non-zero for success, zero for failure.
 */

static int open_decoder(LHAReader *reader)
{
	// Can only read from a normal file.

	if (reader->curr_file_type != CURR_FILE_NORMAL) {
		return 0;
	}

	reader->inner_decoder = lha_basic_reader_decode(reader->reader);

	if (reader->inner_decoder == NULL) {
		return 0;
	}

	// Some archives generated by MacLHA have a MacBinary header
	// attached to the start, which contains MacOS-specific
	// metadata about the compressed file. These are identified
	// and stripped off, using a "passthrough" decoder.

	if (reader->curr_file->os_type == LHA_OS_TYPE_MACOS) {
		reader->decoder = lha_macbinary_passthrough(
		    reader->inner_decoder, reader->curr_file);

		if (reader->decoder == NULL) {
			return 0;
		}
	} else {
		reader->decoder = reader->inner_decoder;
	}

	return 1;
}

LHAReader *lha_reader_new(LHAInputStream *stream)
{
	LHABasicReader *basic_reader;
	LHAReader *reader;

	reader = (LHAReader *) calloc(1, sizeof(LHAReader));

	if (reader == NULL) {
		return NULL;
	}

	basic_reader = lha_basic_reader_new(stream);

	if (basic_reader == NULL) {
		free(reader);
		return NULL;
	}

	reader->reader = basic_reader;
	reader->curr_file = NULL;
	reader->curr_file_type = CURR_FILE_START;
	reader->decoder = NULL;
	reader->inner_decoder = NULL;
	reader->dir_stack = NULL;
	reader->dir_policy = LHA_READER_DIR_END_OF_DIR;
	reader->deferred_symlinks = NULL;

	return reader;
}

void lha_reader_free(LHAReader *reader)
{
	LHAFileHeader *header;

	// Shut down the current decoder, if there is one.

	close_decoder(reader);

	// Free any file headers in the stack.

	while (reader->dir_stack != NULL) {
		header = reader->dir_stack;
		reader->dir_stack = header->_next;
		lha_file_header_free(header);
	}

	lha_basic_reader_free(reader->reader);
	free(reader);
}

/**
 * Check if the directory at the top of the stack should be popped.
 *
 * Extracting a directory is a two stage process; after the directory
 * is created, it is pushed onto the directory stack. Later the
 * directory must be popped off the stack and its metadata applied.
 *
 * @param reader         Pointer to the LHA reader structure.
 * @return               Non-zero if there is a directory at the top of
 *                       the stack that should be popped.
 */

static int end_of_top_dir(LHAReader *reader)
{
	LHAFileHeader *input;

	// No directories to pop?

	if (reader->dir_stack == NULL) {
		return 0;
	}

	// Once the end of the input stream is reached, all that is
	// left to do is pop off the remaining directories.

	input = lha_basic_reader_curr_file(reader->reader);

	if (input == NULL) {
		return 1;
	}

	switch (reader->dir_policy) {

		// Shouldn't happen?

		case LHA_READER_DIR_PLAIN:
		default:
			return 1;

		// Don't process directories until we reach the end of
		// the input stream.

		case LHA_READER_DIR_END_OF_FILE:
			return 0;

		// Once we reach a file from the input that is not within
		// the directory at the top of the stack, we have reached
		// the end of that directory, so we can pop it off.

		case LHA_READER_DIR_END_OF_DIR:
			return input->path == NULL
			    || strncmp(input->path,
			               reader->dir_stack->path,
			               strlen(reader->dir_stack->path)) != 0;
	}
}

// Read the next file from the input stream.

LHAFileHeader *lha_reader_next_file(LHAReader *reader)
{
	// Free the current decoder if there is one.

	close_decoder(reader);

	// No point continuing once the end of the input stream has
	// been reached.

	if (reader->curr_file_type == CURR_FILE_EOF) {
		return NULL;
	}

	// Advance to the next file from the input stream?
	// Don't advance until we've done the fake directories first.

	if (reader->curr_file_type == CURR_FILE_START
	 || reader->curr_file_type == CURR_FILE_NORMAL) {
		lha_basic_reader_next_file(reader->reader);
	}

	// If the last file we returned was a 'fake' directory, we must
	// now unreference it.

	if (reader->curr_file_type == CURR_FILE_FAKE_DIR) {
		lha_file_header_free(reader->curr_file);
	}

	// Pop off all appropriate directories from the stack first.

	if (end_of_top_dir(reader)) {
		reader->curr_file = reader->dir_stack;
		reader->dir_stack = reader->dir_stack->_next;
		reader->curr_file_type = CURR_FILE_FAKE_DIR;
	} else {
		reader->curr_file = lha_basic_reader_curr_file(reader->reader);
		reader->curr_file_type = CURR_FILE_NORMAL;
	}

	// Once we reach the end of the file, there may be deferred
	// symbolic links still to extract, so process those before
	// giving up and declaring end of file.

	if (reader->curr_file == NULL) {
		if (reader->deferred_symlinks != NULL) {
			reader->curr_file = reader->deferred_symlinks;
			reader->curr_file_type = CURR_FILE_DEFERRED_SYMLINK;

			reader->deferred_symlinks =
			    reader->deferred_symlinks->_next;
			reader->curr_file->_next = NULL;
		} else {
			reader->curr_file_type = CURR_FILE_EOF;
		}
	}

	return reader->curr_file;
}

size_t lha_reader_read(LHAReader *reader, void *buf, size_t buf_len)
{
	// The first time that we try to read the current file, we
	// must create the decoder to decompress it.

	if (reader->decoder == NULL) {
		if (!open_decoder(reader)) {
			return 0;
		}
	}

	// Read from decoder and return the result.

	return lha_decoder_read(reader->decoder, (uint8 *)buf, buf_len);
}

int lha_reader_current_is_fake(LHAReader *reader)
{
	return reader->curr_file_type == CURR_FILE_FAKE_DIR
	    || reader->curr_file_type == CURR_FILE_DEFERRED_SYMLINK;
}
