#include <command.h>
#include <linux/stddef.h>
#include <linux/sizes.h>
#include <memalign.h>
#include <utility.h>
#include <errno.h>
#include <blk.h>
#include <mmc.h>
#include <debug_impl.h>
#include "../../../../Customization/Mediatek/console_lock/include/ce_ops_impl.h"
#include "../../../../Mediatek-internal/impl/system/include/utility.h"
#include "console_impl.h"

int mdrv_efuse_read_subbank_reg_U32(unsigned char u8SubBank, unsigned int *pu32RegVal);

int do_usbboot_check(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{

	unsigned short u16SubBank = 0x43; // User area, bit0 for shipsetting bit.
	unsigned int u32RegVal = 0;
	int i_rtn;
	int ret = 0;
	struct ce_ops ops = { };

	if (is_rel_build() == 0){
            printf("Dev build(MTK OTP), skip console lock usb boot check! \n");
            return ret;
	}

	if (get_boot_device() == EN_BOOT_DEVICE_USB) {
		printf("boot device is usb. check eFuse shipsetting bit.\n");
		i_rtn = mdrv_efuse_read_subbank_reg_U32((unsigned char)u16SubBank, &u32RegVal);
		if (i_rtn != 0) {
			UBOOT_ERROR("{%s,%d} mdrv_efuse_read_subbank_reg_U32(u8SubBank:0x%X,) => i_rtn:%d\n", __func__, __LINE__, u16SubBank, i_rtn);
			while (1)
				;
		}
		if (u32RegVal & 1) {
			printf("efuse shipsetting bit is set. Checking console lock status...\n");
			if (ce_ops_init(&ops)) {
				UBOOT_ERROR("ce_ops_init fails.\n");
				while (1)
					;
			}
			if (!ce_ops_cu_read(&ops)) {
				UBOOT_ERROR("usb boot is not allowed. please unlock console first.\n");
				while (1)
					;
			}
			printf("usb boot is allowed.\n");
		} else {
			printf("efuse shipsetting bit is not set.\n");
		}
	}
	return ret;
}

U_BOOT_CMD(
	usbboot_check, 1, 0, do_usbboot_check,
	"Check if usb boot is allowed",
	NULL
);