/*
 * Created by jiaqiang.ye@lnxall.com
 *
 * get_facini for EM1000 device
 *
 * 2023/10/31
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "nvmem.h"
#include "lnxall_facini.h"

int main(int argc, char *argv[])
{
	nvmem_t * pnv;
	int offs, num, prefix;
	struct lnxall_facini * pfi;

	num = 0x1;
	prefix = 1;
	pfi = NULL;
	pnv = nvmem_create();
	if (pnv == NULL) {
		fputs("Error, nvmem_create has failed.\n", stderr);
		fflush(stderr);
		return 1;
	}

	nvmem_init(pnv, NULL);

	pfi = (struct lnxall_facini *) malloc(sizeof(*pfi));
	if (pfi == NULL) {
		fputs("Error, system out of memory!\n", stderr);
		fflush(stderr);
		nvmem_free(pnv);
		return 2;
	}

	offs = facini_find(pnv, pfi);
	if (offs < 0) {
		fputs("Error, no valid factory information found.\n", stderr);
		fflush(stderr);
		nvmem_free(pnv);
		return 3;
	}

	if (num < argc && strcmp(argv[1], "-n") == 0) {
		prefix = 0;
		num = 0x2;
	}

	nvmem_free(pnv);
	pnv = NULL;

	while (num < argc) {
		const char * what;
		what = argv[num++];
		if (what == NULL || what[0] == '\0')
			break;

		if (strcasecmp(what, "sn") == 0) {
			fprintf(stdout, "%s%s\n", prefix ? "SN=" : "", pfi->sn);
			fflush(stdout);
		} else if (strcasecmp(what, "mac") == 0) {
			fprintf(stdout, "%s%s\n", prefix ? "MAC=" : "", pfi->mac);
			fflush(stdout);
		} else if (strcasecmp(what, "date") == 0) {
			fprintf(stdout, "%s%s\n", prefix ? "DATE=" : "", pfi->date);
			fflush(stdout);
		} else if (strcasecmp(what, "hwver") == 0) {
			fprintf(stdout, "%s%s\n", prefix ? "HWVER=" : "", pfi->hwver);
			fflush(stdout);
		} else if (strcasecmp(what, "product") == 0) {
			fprintf(stdout, "%s%s\n", prefix ? "PRODUCT=" : "", pfi->product);
			fflush(stdout);
		} else {
			fprintf(stderr, "Error, unknown ENV: %s\n", what);
			fflush(stderr);
		}
	}

	free(pfi);
	return 0;
}
