/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* Copyright  (C) [2020]  MediaTek Inc. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/

#include <common.h>
#include <dtbo.h>
#include <mtk_dtbo.h>
#include <debug_impl.h>
#include <malloc.h>
#include <fdt_support.h>
#include <iniutility.h>
#include <utility.h>
#ifdef CONFIG_DATA_SEPARATION
#include <mtk_dataindex.h>
#define WDT_SECTION		"WDT"
#define WDT_KEY			"WDT_INI_FILE"
#define PANEL_MIRROR_SECTION			"MISC_MIRROR_CFG"
#define PANEL_MIRROR_KEY			"m_pIniMirrorCfgFile"
#define PANEL_SSC_SECTION			"MISC_SSC_CFG"
#define PANEL_SSC_KEY			"m_pSSC_File"
#define CONSOLE_SECTION		"CONSOLE"
#define CONSOLE_KEY		"CONSOLE_INI_FILE"
#endif

DECLARE_GLOBAL_DATA_PTR;

#define DEFAULT_WDT_PART	"tvconfig"
#define DEFAULT_WDT_INI		"/config/wdt.ini"

#define DEFAULT_PANEL_MIRROR_PART	"tvconfig"
#define DEFAULT_PANEL_MIRROR_INI	"/config/panel/mirror_cfg.ini"

#define DEFAULT_PANEL_SSC_PART	"tvconfig"
#define DEFAULT_PANEL_SSC_INI	"/config/panel/ssc_cfg.ini"

#define DEFAULT_CONSOLE_PART	"tvconfig"
#define DEFAULT_CONSOLE_INI	"/config/console.ini"

#define WDT_NODE_PATH		"/wdt0"
#define NEW_PROP_NAME		"status"
#define NEW_PROP_VAL		"disable"

#define CONSOLE_UART_NODE_PATH  "/UART0"
#define CONSOLE_HDMI_PROP_NAME  "console-hdmi"

static struct wdt_info wdt_sts;
static struct panel_mirror_info mirror_info;
static struct console_info con_info;

static int fdt_appendprop_from_path(void *fdt, const char *path,
			const char *name, const void *val, int len)
{
	int nodeoffset;
	int ret;

	nodeoffset = fdt_path_offset(fdt, path);
	if (nodeoffset < 0) {
		UBOOT_DEBUG("fdt_path_offset Fail\n");
		return -1;
	}
	ret = fdt_appendprop(fdt, nodeoffset, name, val, len);
	if (ret < 0) {
		UBOOT_DEBUG("WDT OVERLAY Fail ret:%d\n",ret);
		return -1;
	}
	return 0;
}

static int overlay_watchdog_settings(void)
{
	int ret;
	void* dtb_addr = (void*)get_dtb_image_address();
#ifdef CONFIG_DATA_SEPARATION
	char part[PART_NAME_SIZE], filepath[FILE_PATH_SIZE];
	const char *relpath;
#endif
    static int watchdog_read_inited = 0;

    if (watchdog_read_inited == 1)
    {
        goto watchdog_setting;
    }

	memset(&wdt_sts, 0, sizeof(wdt_sts));
#ifdef CONFIG_DATA_SEPARATION
	memset(part, 0, sizeof(part));
	memset(filepath, 0, sizeof(filepath));
	if(dataindex_get_key(filepath, FILE_PATH_SIZE, WDT_SECTION, WDT_KEY, NULL) == 0){
		if(dataindex_resolve_path(part, PART_NAME_SIZE, &relpath, filepath) == 0){
			ret = get_wdt_info(part, relpath, &wdt_sts);
			if(ret < 0){
				UBOOT_DEBUG("Read wdt information failure with data separation.\n");
				/*read from watchdog.ini*/
				ret = get_wdt_info(DEFAULT_WDT_PART, DEFAULT_WDT_INI, &wdt_sts);
			}
		}else{
			UBOOT_DEBUG("resolve path fail: %s",filepath);
			/*read from watchdog.ini*/
			ret = get_wdt_info(DEFAULT_WDT_PART, DEFAULT_WDT_INI, &wdt_sts);
		}
	}else{
		UBOOT_DEBUG("cannot get %s:%s from dataindex file\n",WDT_SECTION,WDT_KEY);
#endif
		/*read from watchdog.ini*/
		ret = get_wdt_info(DEFAULT_WDT_PART, DEFAULT_WDT_INI, &wdt_sts);
#ifdef CONFIG_DATA_SEPARATION
	}
#endif

	if (ret < 0) {
		UBOOT_DEBUG("cannot wdt read /config/wdt.ini from tvconfig\n");
	}
    watchdog_read_inited = 1;

watchdog_setting:
	UBOOT_DEBUG("wdt_sts.status:%s\n",wdt_sts.status);

	/*overlay watchdog0 device node*/
	ret = fdt_appendprop_from_path((void *)dtb_addr, WDT_NODE_PATH,
			NEW_PROP_NAME, wdt_sts.status, strlen(wdt_sts.status)+1);
	if (ret < 0) {
		UBOOT_DEBUG("ini overlay Fail ret:%d\n",ret);
	}
	return ret;
}

static int overlay_panel_ssc_settings(void)
{
	void* dtb_addr = (void*)get_dtb_image_address();
	char *dtb_path = "/video_out/spread_spectrum_info";
	char *dtb_nameEn = "ssc_ctrl_en";
	char *dtb_nameMo = "ssc_modulation";
	char *dtb_nameDe = "ssc_deviation";
	struct panel_ssc_info ssc_info;
	const struct fdt_property *fdt_prop;
	int nodeoffset;
	u32 value_old, value_new;
	int ret;
#ifdef CONFIG_DATA_SEPARATION
	char part[PART_NAME_SIZE], filepath[FILE_PATH_SIZE];
	const char *relpath;
#endif

	memset(&ssc_info, 0, sizeof(ssc_info));
#ifdef CONFIG_DATA_SEPARATION
	memset(part, 0, sizeof(part));
	memset(filepath, 0, sizeof(filepath));
	if(dataindex_get_key(filepath, FILE_PATH_SIZE, PANEL_SSC_SECTION, PANEL_SSC_KEY, NULL) == 0){
		if(dataindex_resolve_path(part, PART_NAME_SIZE, &relpath, filepath) == 0){
			// read from ssc_cfg.ini
			ret = get_panel_ssc_info(part, relpath, &ssc_info);
			if(ret < 0){
				UBOOT_DEBUG("Read panel ssc information failure with data separation.\n");
				// read from ssc_cfg.ini
				ret = get_panel_ssc_info(DEFAULT_PANEL_SSC_PART, DEFAULT_PANEL_SSC_INI, &ssc_info);
			}
		}else{
			UBOOT_DEBUG("resolve path fail: %s",filepath);
			// read from ssc_cfg.ini
			ret = get_panel_ssc_info(DEFAULT_PANEL_SSC_PART, DEFAULT_PANEL_SSC_INI, &ssc_info);
		}
	}else{
		UBOOT_DEBUG("cannot get %s:%s from dataindex file\n",PANEL_SSC_SECTION,PANEL_SSC_KEY);
#endif
		ret = get_panel_ssc_info(DEFAULT_PANEL_SSC_PART, DEFAULT_PANEL_SSC_INI, &ssc_info);
#ifdef CONFIG_DATA_SEPARATION
	}
#endif

	if (ret < 0) {
        UBOOT_DEBUG("Cannot read %s:%s\n", DEFAULT_PANEL_SSC_PART, DEFAULT_PANEL_SSC_INI);
		return -1;
	}
	UBOOT_DEBUG("ssc_info.ssc_enable:%d\n", ssc_info.ssc_enable);
	UBOOT_DEBUG("ssc_info.ssc_modulation:%d\n", ssc_info.ssc_modulation);
	UBOOT_DEBUG("ssc_info.ssc_deviation:%d\n", ssc_info.ssc_deviation);

	if (ssc_info.ssc_overwrite_enable == false){
		UBOOT_DEBUG("Disable Overlay\n");
		return 0;
	}
    // Update dts if the setting is valid
	// ssc_enable
	nodeoffset = fdt_path_offset(dtb_addr, dtb_path);
	if (nodeoffset < 0) {
		UBOOT_ERROR("Cannot get offset of '%s'\n", dtb_path);
		return -1;
	}
	fdt_prop = fdt_get_property(dtb_addr, nodeoffset, dtb_nameEn, &ret);
	if (fdt_prop == NULL || ret < sizeof(int)) { // @ret is data size
		UBOOT_ERROR("Cannot get prop '%s'\n", dtb_nameEn);
		return -1;
	}
	value_old = fdt32_to_cpu(*((__be32 *)fdt_prop->data));
	value_new = ssc_info.ssc_enable;
	ret = fdt_setprop_u32(dtb_addr, nodeoffset, dtb_nameEn, value_new);
	if (ret != 0) {
		UBOOT_ERROR("Cannot set prop '%s'\n", dtb_nameEn);
		return -1;
	}
	UBOOT_DEBUG("Set [%s:%s] = %d -> %d (ini: %d)\n",
		dtb_path, dtb_nameEn, value_old, value_new, ssc_info.ssc_enable);

	// ssc_modulation
	nodeoffset = fdt_path_offset(dtb_addr, dtb_path);
	if (nodeoffset < 0) {
		UBOOT_ERROR("Cannot get offset of '%s'\n", dtb_path);
		return -1;
	}
	fdt_prop = fdt_get_property(dtb_addr, nodeoffset, dtb_nameMo, &ret);
	if (fdt_prop == NULL || ret < sizeof(int)) { // @ret is data size
		UBOOT_ERROR("Cannot get prop '%s'\n", dtb_nameMo);
		return -1;
	}
	value_old = fdt32_to_cpu(*((__be32 *)fdt_prop->data));
	value_new = ssc_info.ssc_modulation;
	ret = fdt_setprop_u32(dtb_addr, nodeoffset, dtb_nameMo, value_new);
	if (ret != 0) {
		UBOOT_ERROR("Cannot set prop '%s'\n", dtb_nameMo);
		return -1;
	}
	UBOOT_DEBUG("Set [%s:%s] = %d -> %d (ini: %d)\n",
		dtb_path, dtb_nameMo, value_old, value_new, ssc_info.ssc_modulation);

	// ssc_deviation
	nodeoffset = fdt_path_offset(dtb_addr, dtb_path);
	if (nodeoffset < 0) {
		UBOOT_ERROR("Cannot get offset of '%s'\n", dtb_path);
		return -1;
	}
	fdt_prop = fdt_get_property(dtb_addr, nodeoffset, dtb_nameDe, &ret);
	if (fdt_prop == NULL || ret < sizeof(int)) { // @ret is data size
		UBOOT_ERROR("Cannot get prop '%s'\n", dtb_nameDe);
		return -1;
	}
	value_old = fdt32_to_cpu(*((__be32 *)fdt_prop->data));
	value_new = ssc_info.ssc_deviation;
	ret = fdt_setprop_u32(dtb_addr, nodeoffset, dtb_nameDe, value_new);
	if (ret != 0) {
		UBOOT_ERROR("Cannot set prop '%s'\n", dtb_nameDe);
		return -1;
	}
	UBOOT_DEBUG("Set [%s:%s] = %d -> %d (ini: %d)\n",
		dtb_path, dtb_nameDe, value_old, value_new, ssc_info.ssc_deviation);

	return 0;
}


#define PANEL_MIRROR_VALUE_MASK 0x3
static int overlay_panel_mirror_settings(void)
{
	void* dtb_addr = (void*)get_dtb_image_address();
	char *dtb_path = "/video_out/panel-cus-setting";
	char *dtb_name = "PanelMirrorMode";
	const struct fdt_property *fdt_prop;
	int nodeoffset;
	u32 value_old, value_new;
	int ret;
#ifdef CONFIG_DATA_SEPARATION
	char part[PART_NAME_SIZE], filepath[FILE_PATH_SIZE];
	const char *relpath;
#endif
    static int mirror_read_inited = 0;

    if (mirror_read_inited == 1)
    {
        goto mirror_setting;
    }

	memset(&mirror_info, 0, sizeof(mirror_info));
#ifdef CONFIG_DATA_SEPARATION
	memset(part, 0, sizeof(part));
	memset(filepath, 0, sizeof(filepath));
	if(dataindex_get_key(filepath, FILE_PATH_SIZE, PANEL_MIRROR_SECTION, PANEL_MIRROR_KEY, NULL) == 0){
		if(dataindex_resolve_path(part, PART_NAME_SIZE, &relpath, filepath) == 0){
			// read from mirror_cfg.ini
			ret = get_panel_mirror_info(part, relpath, &mirror_info);
			if(ret < 0){
				UBOOT_DEBUG("Read panel mirror information failure with data separation.\n");
				// read from mirror_cfg.ini
				ret = get_panel_mirror_info(DEFAULT_PANEL_MIRROR_PART, DEFAULT_PANEL_MIRROR_INI, &mirror_info);
			}
		}else{
			UBOOT_DEBUG("resolve path fail: %s",filepath);
			// read from mirror_cfg.ini
			ret = get_panel_mirror_info(DEFAULT_PANEL_MIRROR_PART, DEFAULT_PANEL_MIRROR_INI, &mirror_info);
		}
	}else{
		UBOOT_DEBUG("cannot get %s:%s from dataindex file\n",PANEL_MIRROR_SECTION,PANEL_MIRROR_KEY);
#endif
		ret = get_panel_mirror_info(DEFAULT_PANEL_MIRROR_PART, DEFAULT_PANEL_MIRROR_INI, &mirror_info);
#ifdef CONFIG_DATA_SEPARATION
	}
#endif

	if (ret < 0) {
		UBOOT_ERROR("Cannot read %s:%s\n", DEFAULT_PANEL_MIRROR_PART, DEFAULT_PANEL_MIRROR_INI);
		return -1;
	}
    mirror_read_inited = 1;

mirror_setting:
	UBOOT_DEBUG("mirror_info.valid:%d\n", mirror_info.valid);
	UBOOT_DEBUG("mirror_info.mirror_mode:%d\n", mirror_info.mirror_mode);

	// Update dts if the setting is valid
	if (mirror_info.valid == true) {
		nodeoffset = fdt_path_offset(dtb_addr, dtb_path);
		if (nodeoffset < 0) {
			UBOOT_ERROR("Cannot get offset of '%s'\n", dtb_path);
			return -1;
		}
		fdt_prop = fdt_get_property(dtb_addr, nodeoffset, dtb_name, &ret);
		if (fdt_prop == NULL || ret < sizeof(int)) { // @ret is data size
			UBOOT_ERROR("Cannot get prop '%s'\n", dtb_name);
			return -1;
		}
		value_old = fdt32_to_cpu(*((__be32 *)fdt_prop->data));
		value_new = (value_old ^ mirror_info.mirror_mode) & PANEL_MIRROR_VALUE_MASK;
		ret = fdt_setprop_u32(dtb_addr, nodeoffset, dtb_name, value_new);
		if (ret != 0) {
			UBOOT_ERROR("Cannot set prop '%s'\n", dtb_name);
			return -1;
		}
		UBOOT_DEBUG("Set [%s:%s] = %d -> %d (ini: %d)\n",
			dtb_path, dtb_name, value_old, value_new, mirror_info.mirror_mode);
	}
	return 0;
}

static int overlay_console_switch_ini(void)
{
	int ret = 0;
#ifdef CONFIG_DATA_SEPARATION
	char part[PART_NAME_SIZE], filepath[FILE_PATH_SIZE];
	const char *relpath;
#endif
    static int console_read_inited = 0;

    if (console_read_inited == 1)
    {
        goto console_setting;
    }

	// parse ini for console_onoff and console_hdmi
	memset(&con_info, 0, sizeof(con_info));

#ifdef CONFIG_DATA_SEPARATION
	memset(part, 0, sizeof(part));
	memset(filepath, 0, sizeof(filepath));
	if (dataindex_get_key(filepath, FILE_PATH_SIZE, CONSOLE_SECTION, CONSOLE_KEY, NULL) == 0) {
		if (dataindex_resolve_path(part, PART_NAME_SIZE, &relpath, filepath) == 0) {
			ret = get_console_info(part, relpath, &con_info);
			if (ret < 0) {
				UBOOT_DEBUG("Read console information failure with data separation.\n");
				/*read from console.ini*/
				ret = get_console_info(DEFAULT_CONSOLE_PART, DEFAULT_CONSOLE_INI,
						       &con_info);
			}
		} else {
			UBOOT_DEBUG("resolve path fail: %s",filepath);
			/*read from console.ini*/
			ret = get_console_info(DEFAULT_CONSOLE_PART, DEFAULT_CONSOLE_INI,
					       &con_info);
		}
	} else {
		UBOOT_DEBUG("cannot get %s:%s from dataindex file\n", CONSOLE_SECTION, CONSOLE_KEY);
#endif
		/*read from console.ini*/
		ret = get_console_info(DEFAULT_CONSOLE_PART, DEFAULT_CONSOLE_INI, &con_info);
#ifdef CONFIG_DATA_SEPARATION
	}
#endif

	if (ret < 0) {
		UBOOT_DEBUG("cannot read "DEFAULT_CONSOLE_INI" from "DEFAULT_CONSOLE_PART"\n");
		return 0;
	}
    console_read_inited = 1;

console_setting:
	UBOOT_DEBUG("console_onoff = %s\n", con_info.console_onoff);
	UBOOT_DEBUG("console_hdmi = %s\n", con_info.console_hdmi);

    if (!strcmp(con_info.console_onoff, "on")) {
        UBOOT_DEBUG("switch console on in console.ini, delete bootarg.\n");
#ifdef CONFIG_SILENT_CONSOLE
        env_set("uboot_console_off", NULL);
#endif
        gd->flags &= ~GD_FLG_SILENT;
        // module parameter when UART driver is kernel module
        del_bootargs("8250_mtk_tv.log_disable", 0);
        // module parameter when UART driver is build-in
        del_bootargs("log_disable", 0);
    }
    else if (!strcmp(con_info.console_onoff, "off"))
    {
        UBOOT_DEBUG("switch console off in console.ini, add bootarg.\n");
#ifdef CONFIG_SILENT_CONSOLE
        env_set("uboot_console_off", "true");
#endif
        gd->flags |= GD_FLG_SILENT;
        // module parameter when UART driver is build-in
        add_bootargs("log_disable", "log_disable=1", 0);
        // module parameter when UART driver is kernel module
        add_bootargs("8250_mtk_tv.log_disable", "8250_mtk_tv.log_disable=1", 0);
    }
    else
    {
        UBOOT_DEBUG("switch console on in console.ini default setting, delete bootarg.\n");
#ifdef CONFIG_SILENT_CONSOLE
        env_set("uboot_console_off", NULL);
#endif
        gd->flags &= ~GD_FLG_SILENT;
        // module parameter when UART driver is kernel module
        del_bootargs("8250_mtk_tv.log_disable", 0);
        // module parameter when UART driver is build-in
        del_bootargs("log_disable", 0);
    }

    if (!(gd->flags & GD_FLG_SILENT))
    {
        void *dtb_addr = (void *)get_dtb_image_address();
        u32 con_hdmi_prop[1];

        con_hdmi_prop[0] = 0;

        if (strcmp(con_info.console_hdmi, "on"))
        {
            // default not switch to hdmi
            UBOOT_DEBUG("console_switch finished\n");
            return 0;
        }

        UBOOT_INFO("Marking switch console to hdmi in DTB\n");

        /*
         * overlay console UART0 device node, add property, driver only check property
         * existence now
         */
        con_hdmi_prop[0] = 1;
        ret = fdt_appendprop_from_path((void *)dtb_addr, CONSOLE_UART_NODE_PATH,
                                       CONSOLE_HDMI_PROP_NAME, con_hdmi_prop,
                                       sizeof(con_hdmi_prop));
        if (ret < 0)
        {
            UBOOT_ERROR("ini overlay console-hdmi Fail ret:%d\n", ret);
        }
    }

	UBOOT_DEBUG("console_switch finished\n");
	return 0;
}

int overlay_ini_settings(void)
{
    int ret, ret1;

	ret = overlay_console_switch_ini();
	if (ret < 0) {
		UBOOT_ERROR("console switch ini failure with %d\n", ret);
	}

	ret = overlay_watchdog_settings();
	if (ret < 0) {
		UBOOT_ERROR("watchdog dtbo failure with %d\n", ret);
	}

	ret = overlay_panel_mirror_settings();
	if (ret < 0) {
		UBOOT_ERROR("panel mirror dtbo failure with %d\n", ret);
	}

    ret1 = overlay_panel_ssc_settings();
    if (ret1 < 0)
    {
        UBOOT_DEBUG("panel ssc dtbo not work %d\n", ret1);
    }
	return ret;
}
