// SPDX-FileCopyrightText: 2009-2019 pancake <pancake@nopcode.org>
// SPDX-FileCopyrightText: 2009-2019 nibble <nibble.ds@gmail.com>
// SPDX-License-Identifier: LGPL-3.0-only

#include <rz_types.h>
#include <rz_util.h>
#include <rz_lib.h>
#include <rz_bin.h>
#include <rz_magic.h>

#if RZ_SYS_ENDIAN == RZ_SYS_ENDIAN_LITTLE
#define ANY_DEFAULT_ENDIANNESS false
#else
#define ANY_DEFAULT_ENDIANNESS true
#endif

static char *get_filetype(RzBuffer *b) {
	ut8 buf[4096] = { 0 };
	char *res = NULL;
	RzMagic *ck = rz_magic_new();
	if (!ck) {
		return NULL;
	}
	RzPath *sys_path = rz_path_new();
	if (!sys_path) {
		rz_magic_free(ck);
		return NULL;
	}
	char *tmp = NULL;
	// TODO: dir.magic not honored here
	char *m = rz_path_system(sys_path, RZ_SDB_MAGIC);
	if (!m) {
		rz_magic_free(ck);
		rz_path_free(sys_path);
		return NULL;
	}
	rz_magic_load(ck, m);
	free(m);
	rz_buf_read_at(b, 0, buf, sizeof(buf));
	tmp = rz_magic_buffer(ck, buf, sizeof(buf));
	if (tmp) {
		res = rz_str_dup(tmp);
	}
	free(tmp);
	rz_magic_free(ck);
	rz_path_free(sys_path);
	return res;
}

static RzBinInfo *info(RzBinFile *bf) {
	RzBinInfo *ret = RZ_NEW0(RzBinInfo);
	if (!ret) {
		return NULL;
	}
	ret->lang = "";
	ret->file = rz_str_dup(bf->file);
	ret->type = get_filetype(bf->buf);
	ret->has_retguard = false;
	ret->big_endian = ANY_DEFAULT_ENDIANNESS;
	return ret;
}

static bool load_buffer(RzBinFile *bf, RzBinObject *obj, RzBuffer *buf, Sdb *sdb) {
	return true;
}

static void destroy(RzBinFile *bf) {
	rz_buf_free(bf->o->bin_obj);
}

static ut64 baddr(RzBinFile *bf) {
	return 0LL;
}

RzBinPlugin rz_bin_plugin_any = {
	.name = "any",
	.desc = "Dummy format binary",
	.license = "LGPL3",
	.author = "nibble",
	.load_buffer = &load_buffer,
	.destroy = &destroy,
	.baddr = &baddr,
	.info = info,
};

#ifndef RZ_PLUGIN_INCORE
RZ_API RzLibStruct rizin_plugin = {
	.type = RZ_LIB_TYPE_BIN,
	.data = &rz_bin_plugin_any,
	.version = RZ_VERSION
};
#endif
