/* Copyright 2011 Fredrik Wikstrom. All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
**    notice, this list of conditions and the following disclaimer.
**
** 2. Redistributions in binary form must reproduce the above copyright
**    notice, this list of conditions and the following disclaimer in the
**    documentation and/or other materials provided with the distribution.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
** POSSIBILITY OF SUCH DAMAGE.
*/

#include "vditool.h"

static BOOL is_null_terminated_text (const uint8 *data, int32 len);

VDIFILE *open_vdi (CONST_STRPTR filename, int32 mode) {
	VDIFILE *vdi;
	vdi = IExec->AllocVecTags(sizeof(VDIFILE),
		AVT_ClearWithValue, 0,
		TAG_END);
	if (vdi) {
		vdi->filename = filename;
		vdi->header = IExec->AllocVecTags(sizeof(vdi_header_t),
			AVT_ClearWithValue, 0,
			TAG_END);
		if (vdi->header) {
			vdi->file = IDOS->Open(filename, mode);
			if (vdi->file) {
				return vdi;
			} else {
				IDOS->PrintFault(IDOS->IoErr(), filename);
			}
		} else {
			IDOS->PrintFault(ERROR_NO_FREE_STORE, PROGNAME);
		}
		close_vdi(vdi);
	} else {
		IDOS->PrintFault(ERROR_NO_FREE_STORE, PROGNAME);
	}
	return NULL;
}

void close_vdi (VDIFILE *vdi) {
	if (vdi) {
		IDOS->Close(vdi->file);
		IExec->FreeVec(vdi->block_map);
		IExec->FreeVec(vdi->header);
		IExec->FreeVec(vdi);
	}
}

BOOL write_header (VDIFILE *vdi) {
	int32 bytes;
	if (!IDOS->ChangeFilePosition(vdi->file, 0, OFFSET_BEGINNING)) {
		IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		return FALSE;
	}
	if ((bytes = IDOS->Write(vdi->file, vdi->header, sizeof(vdi_header_t)))
		!= sizeof(vdi_header_t))
	{
		IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		IDOS->FPrintf(StdErr, "%s: failed to write vdi header\n", vdi->filename);
		return FALSE;
	}
	return TRUE;
}

BOOL read_header (VDIFILE *vdi) {
	vdi_header_t *header;
	int32 bytes;
	if (!IDOS->ChangeFilePosition(vdi->file, 0, OFFSET_BEGINNING)) {
		IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		return FALSE;
	}
	if ((bytes = IDOS->Read(vdi->file, vdi->header, sizeof(vdi_header_t)))
		!= sizeof(vdi_header_t))
	{
		if (bytes == -1) {
			IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		}
		IDOS->FPrintf(StdErr, "%s: failed to read vdi header\n", vdi->filename);
		return FALSE;
	}
	header = vdi->header;
	if (!is_null_terminated_text(header->signature, 64) ||
		!strstr(header->signature, "VirtualBox Disk Image") ||
		rle32(&header->sig32) != VDI_MAGIC)
	{
		IDOS->FPrintf(StdErr, "%s: not a vdi file\n", vdi->filename);
		return FALSE;
	}
	vdi->offset_blocks = rle32(&header->offset_blocks);
	vdi->offset_data = rle32(&header->offset_data);
	vdi->block_size = rle32(&header->block_size);
	vdi->total_blocks = rle32(&header->blocks_in_hdd);
	return TRUE;
}

BOOL write_block_map (VDIFILE *vdi) {
	uint32 block_map_size;
	int32 bytes;
	block_map_size = vdi->total_blocks * sizeof(uint32);
	if (!IDOS->ChangeFilePosition(vdi->file, vdi->offset_blocks, OFFSET_BEGINNING)) {
		IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		return FALSE;
	}
	if (!vdi->block_map) {
		vdi->block_map = IExec->AllocVecTags(block_map_size,
			AVT_ClearWithValue, 0xff,
			TAG_END);
		if (!vdi->block_map) {
			IDOS->PrintFault(ERROR_NO_FREE_STORE, PROGNAME);
		}
	}
	if ((bytes = IDOS->Write(vdi->file, vdi->block_map, block_map_size))
		!= block_map_size)
	{
		IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		IDOS->FPrintf(StdErr, "%s: failed to write block map\n", vdi->filename);
		return FALSE;
	}
	return TRUE;
}

BOOL read_block_map (VDIFILE *vdi) {
	uint32 block_map_size;
	int32 bytes;
	block_map_size = vdi->total_blocks * sizeof(uint32);
	if (!IDOS->ChangeFilePosition(vdi->file, vdi->offset_blocks, OFFSET_BEGINNING)) {
		IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		return FALSE;
	}
	if (!vdi->block_map) {
		vdi->block_map = IExec->AllocVecTagList(block_map_size, NULL);
		if (!vdi->block_map) {
			IDOS->PrintFault(ERROR_NO_FREE_STORE, PROGNAME);
		}
	}
	if ((bytes = IDOS->Read(vdi->file, vdi->block_map, block_map_size))
		!= block_map_size)
	{
		if (bytes == -1) {
			IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		}
		IDOS->FPrintf(StdErr, "%s: failed to read block map\n", vdi->filename);
		return FALSE;
	}
	return TRUE;
}

BOOL write_block (VDIFILE *vdi, const uint8 *buffer, uint32 block) {
	uint64 file_offset;
	int32 bytes;
	file_offset = (uint64)vdi->offset_data + (uint64)rle32(&vdi->block_map[block]) * (uint64)vdi->block_size;
	if (!IDOS->ChangeFilePosition(vdi->file, file_offset, OFFSET_BEGINNING)) {
		IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		return FALSE;
	}
	if ((bytes = IDOS->Write(vdi->file, buffer, vdi->block_size))
		!= vdi->block_size)
	{
		stop_progress();
		IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		IDOS->FPrintf(StdErr, "%s: failed to write block %lu\n", vdi->filename, block);
		return FALSE;
	}
	return TRUE;
}

BOOL read_block (VDIFILE *vdi, uint8 *buffer, uint32 block) {
	uint64 file_offset;
	int32 bytes;
	file_offset = (uint64)vdi->offset_data + (uint64)rle32(&vdi->block_map[block]) * (uint64)vdi->block_size;
	if (!IDOS->ChangeFilePosition(vdi->file, file_offset, OFFSET_BEGINNING)) {
		IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		return FALSE;
	}
	if ((bytes = IDOS->Read(vdi->file, buffer, vdi->block_size))
		!= vdi->block_size)
	{
		stop_progress();
		if (bytes == -1) {
			IDOS->PrintFault(IDOS->IoErr(), vdi->filename);
		}
		IDOS->FPrintf(StdErr, "%s: failed to write block %lu\n", vdi->filename, block);
		return FALSE;
	}
	return TRUE;
}

static BOOL is_null_terminated_text (const uint8 *data, int32 len) {
	uint8 c;
	while (len--) {
		c = *data++;
		if (c == 0) {
			return TRUE;
		}
		if (c < 9 || (c < 32 && c > 13) || c == 127) {
			return FALSE;
		}
	}
	return FALSE;
}
