/* $Id: brcm.c,v 1.1.1.1 2009/02/21 21:25:19 khorben Exp $ */
/* Copyright (c) 2007 khorben of Uberwall */
/* This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */



#include <stdint.h>
#include "plugin.h"


/* brcm */
/* public */
/* types */
#pragma pack(1)
struct brcm
{
	char magic[4];
	uint32_t sections;
};

struct brcm_section
{
	uint32_t type;
	uint32_t size;
	uint32_t padding;
};
#pragma pack()

enum brcm_type { TYPE_FLASH = 0x12, TYPE_DISK = 0x13, TYPE_TAG = 0x15 };


/* variables */
/* magic */
static unsigned char sig[] = "BRCM";

static PluginMagic brcm_magic[] =
{
	{ sizeof(struct brcm),	0,	sig,	sizeof(sig)-1	},
	{ 0,			0,	NULL,	0		}
};


/* functions */
static int brcm_callback(PluginHelper * ph, int signature, FILE * fp);


/* plugin */
Plugin plugin =
{
	PT_ARCHIVE,
	"BRCM",
	brcm_magic,
	brcm_callback
};


/* private */
/* functions */
/* brcm_callback */
static int _callback_section(PluginHelper * ph, struct brcm_section * buf);

static int brcm_callback(PluginHelper * ph, int signature, FILE * fp)
{
	int score = 0;
	struct brcm hdr;
	struct brcm_section buf;
	uint32_t i;

	if(fread(&hdr, sizeof(hdr), 1, fp) != 1)
		return -1;
	/* FIXME not endian-proof */
	if(hdr.sections == 0)
	{
		ph->printf(ph, "%s", "no sections\n");
		return 0;
	}
	ph->printf(ph, "%u%s", hdr.sections, " sections:\n");
	for(i = 0; i < hdr.sections; i++)
	{
		if(fread(&buf, sizeof(buf), 1, fp) != 1)
			break;
		score += _callback_section(ph, &buf);
	}
	return score / hdr.sections;
}

static int _callback_section(PluginHelper * ph, struct brcm_section * buf)
{
	struct
	{
		enum brcm_type type;
		char * name;
	} tn[] =
	{
		{ TYPE_FLASH,	"flash"	},
		{ TYPE_DISK,	"disk"	},
		{ TYPE_TAG,	"tag"	},
		{ 0,		NULL	}
	};
	int i;

	for(i = 0; tn[i].name != NULL && buf->type != tn[i].type; i++);
	ph->printf(ph, "%s%s%s%u\n", "type ",
			tn[i].name != NULL ? tn[i].name : "unknown",
			", size ", buf->size);
	return tn[i].name != NULL ? 100 : 0;
}