/******************************************************************************
 * hiperiso.c
 *
 * Copyright (c) 2020, longpanda <admin@hiperiso.net>
 *
 * 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; either version 3 of the
 * License, or (at your option) any later version.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 *
 */

#include <grub/types.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/disk.h>
#include <grub/device.h>
#include <grub/term.h>
#include <grub/partition.h>
#include <grub/file.h>
#include <grub/normal.h>
#include <grub/extcmd.h>
#include <grub/datetime.h>
#include <grub/net.h>
#include <grub/misc.h>
#include <grub/kernel.h>
#include <grub/time.h>
#include <grub/memory.h>
#ifdef GRUB_MACHINE_EFI
#include <grub/efi/efi.h>
#include <grub/efi/memory.h>
#endif
#include <grub/hiperiso.h>
#include "hiperiso_def.h"

GRUB_MOD_LICENSE ("GPLv3+");

int g_hiperiso_debug = 0;
static int g_efi_os = 0xFF;
grub_uint32_t g_hiperiso_plat_data;

#ifdef GRUB_MACHINE_EFI
static HISO_SHIM *g_hiso_shim = NULL;
#endif

void hiperiso_debug(const char *fmt, ...)
{
    va_list args;

    va_start (args, fmt);
    grub_vprintf (fmt, args);
    va_end (args);
}

void hiperiso_str_tolower(char *str)
{
    while (*str)
    {
        *str = grub_tolower(*str);
        str++;
    }
}

void hiperiso_str_toupper(char *str)
{
    while (*str)
    {
        *str = grub_toupper(*str);
        str++;
    }
}

char *hiperiso_str_last(char *str, char ch)
{
    char *pos = NULL;
    char *last = NULL;

    if (!str)
    {
        return NULL;
    }

    for (pos = str; *pos; pos++)
    {
        if (*pos == ch)
        {
            last = pos;
        }
    }

    return last;
}

int hiperiso_str_all_digit(const char *str)
{
    if (NULL == str || 0 == *str)
    {
        return 0;
    }

    while (*str)
    {
        if (*str < '0' || *str > '9')
        {
            return 0;
        }
        str++;
    }

    return 1;
}

int hiperiso_str_all_alnum(const char *str)
{
    if (NULL == str || 0 == *str)
    {
        return 0;
    }

    while (*str)
    {
        if (!grub_isalnum(*str))
        {
            return 0;
        }
    }

    return 1;
}

int hiperiso_str_len_alnum(const char *str, int len)
{
    int i;
    int slen;

    if (NULL == str || 0 == *str)
    {
        return 0;
    }

    slen = grub_strlen(str);
    if (slen <= len)
    {
        return 0;
    }

    for (i = 0; i < len; i++)
    {
        if (!grub_isalnum(str[i]))
        {
            return 0;
        }
    }

    if (str[len] == 0 || grub_isspace(str[len]))
    {
        return 1;
    }

    return 0;
}

char * hiperiso_str_basename(char *path)
{
    char *pos = NULL;

    pos = grub_strrchr(path, '/');
    if (pos)
    {
        pos++;
    }
    else
    {
        pos = path;
    }

    return pos;
}

int hiperiso_str_chrcnt(const char *str, char c)
{
    int n = 0;

    if (str)
    {
        while (*str)
        {
            if (*str == c)
            {
                n++;
            }
            str++;
        }
    }

    return n;
}

int hiperiso_strcmp(const char *pattern, const char *str)
{
    while (*pattern && *str)
    {
        if ((*pattern != *str) && (*pattern != '*'))
            break;

        pattern++;
        str++;
    }

    return (int)(grub_uint8_t)*pattern - (int)(grub_uint8_t)*str;
}

int hiperiso_strncmp (const char *pattern, const char *str, grub_size_t n)
{
    if (n == 0)
        return 0;

    while (*pattern && *str && --n)
    {
        if ((*pattern != *str) && (*pattern != '*'))
            break;

        pattern++;
        str++;
    }

    return (int)(grub_uint8_t)*pattern - (int)(grub_uint8_t)*str;
}

grub_err_t hiperiso_env_int_set(const char *name, int value)
{
    char buf[16];

    grub_snprintf(buf, sizeof(buf), "%d", value);
    return grub_env_set(name, buf);
}

void hiperiso_debug_dump_guid(const char *prefix, grub_uint8_t *guid)
{
    int i;

    if (!g_hiperiso_debug)
    {
        return;
    }

    debug("%s", prefix);
    for (i = 0; i < 16; i++)
    {
        grub_printf("%02x ", guid[i]);
    }
    grub_printf("\n");
}

int hiperiso_is_efi_os(void)
{
    if (g_efi_os > 1)
    {
        g_efi_os = (grub_strstr(GRUB_PLATFORM, "efi")) ? 1 : 0;
    }

    return g_efi_os;
}

void * hiperiso_alloc_chain(grub_size_t size)
{
    void *p = NULL;

    p = grub_malloc(size);
#ifdef GRUB_MACHINE_EFI
    if (!p)
    {
        p = grub_efi_allocate_any_pages(GRUB_EFI_BYTES_TO_PAGES(size));
    }
#endif

    return p;
}

void hiperiso_memfile_env_set(const char *prefix, const void *buf, unsigned long long len)
{
    char name[128];
    char val[64];

    grub_snprintf(name, sizeof(name), "%s_addr", prefix);
    grub_snprintf(val, sizeof(val), "0x%llx", (ulonglong)(ulong)buf);
    grub_env_set(name, val);

    grub_snprintf(name, sizeof(name), "%s_size", prefix);
    grub_snprintf(val, sizeof(val), "%llu", len);
    grub_env_set(name, val);

    return;
}

#ifdef GRUB_MACHINE_EFI
static void hiperiso_get_uefi_version(char *str, grub_size_t len)
{
    grub_efi_uint8_t uefi_minor_1, uefi_minor_2;

    uefi_minor_1 = (grub_efi_system_table->hdr.revision & 0xffff) / 10;
    uefi_minor_2 = (grub_efi_system_table->hdr.revision & 0xffff) % 10;
    grub_snprintf(str, len, "%d.%d", (grub_efi_system_table->hdr.revision >> 16), uefi_minor_1);
    if (uefi_minor_2)
        grub_snprintf(str, len, "%s.%d", str, uefi_minor_2);
}

static void hiperiso_get_pi_version(char *str, grub_size_t len)
{
    grub_uint32_t data = 0;
    grub_efi_uintn_t i = 0;
    grub_efi_guid_t dxest =
        { 0x05ad34ba, 0x6f02, 0x4214, {0x95, 0x2e, 0x4d, 0xa0, 0x39, 0x8e, 0x2b, 0xb9 } };

    for (i = 0; i < grub_efi_system_table->num_table_entries; i++)
    {
        if (grub_memcmp(&dxest, &grub_efi_system_table->configuration_table[i].vendor_guid, 16) == 0)
        {
            grub_memcpy(&data, (char *)grub_efi_system_table->configuration_table[i].vendor_table + 8, 4);
            break;
        }
    }

    grub_snprintf(str, len, "%d.%d", (data >> 16) & 0xFFFF, (data & 0xFFFF) / 10);
}

int hiperiso_set_sb_policy(void)
{
    const char *env = NULL;
    static int set_once = 0;

    /* no need when SecureBoot is disabled */
    if (g_sys_sb == 0)
    {
        return 0;
    }

    /* can only set once */
    if (set_once > 0)
    {
        return 0;
    }
    set_once = 1;

    /* HISO_SECURE_BOOT_POLICY only take affect once during init */
    env = grub_env_get("HISO_SECURE_BOOT_POLICY");
    if (env)
    {
        g_sb_policy = (grub_uint8_t)(env[0] - '0');
    }

    if (g_sb_policy == HISO_SB_POLICY_BYPASS)
    {
        if (g_hiso_shim && g_hiso_shim->ByPassSB)
        {
            g_hiso_shim->ByPassSB();
        }
    }
    else if (g_sb_policy == HISO_SB_POLICY_CHECK)
    {
        if (g_hiso_shim && g_hiso_shim->CheckSB)
        {
            g_hiso_shim->CheckSB();
        }
    }

    return 0;
}

static void hiperiso_get_uefi_sb(void)
{
    grub_uint8_t secure_boot = 0;
    grub_uint8_t setup_mode = 0;
    grub_uint8_t *var = NULL;
    grub_size_t size = 0;
    grub_efi_guid_t global = GRUB_EFI_GLOBAL_VARIABLE_GUID;

    var = grub_efi_get_variable("SecureBoot", &global, &size);
    if (var && size == 1 && *var == 1)
    {
        secure_boot = 1;
    }
    grub_check_free(var);

    size = 0;
    var = grub_efi_get_variable("SetupMode", &global, &size);
    if (var && size == 1 && *var == 1)
    {
        setup_mode = 1;
    }

    if (secure_boot == 1 && setup_mode == 0)
    {
        g_sys_sb = 1;
    }

    grub_check_free(var);
}

static int hiperiso_secure_boot_init(void)
{
    grub_efi_guid_t ProtGuid = HISO_SHIM_POLICY_GUID;

    hiperiso_get_uefi_sb();

    if (g_sys_sb == 0)
    {
        return 0;
    }


    /*
     * When SecureBoot enabled, Hiperiso grub must be launched by Hiperiso Shim.
     * Currently only x86_64 support this feature.
     */
    if (g_hiperiso_plat_data == HISO_PLAT_X86_64_UEFI)
    {
        g_hiso_shim = grub_efi_locate_protocol(&ProtGuid, NULL);
        if (g_hiso_shim == NULL || g_hiso_shim->ByPassSB == NULL ||
            g_hiso_shim->CheckSB == NULL || g_hiso_shim->Launched == NULL)
        {
            grub_cls();
            grub_printf(HISO_WARNING"\n");
            grub_printf(HISO_WARNING"\n");
            grub_printf(HISO_WARNING"\n\n\n");

            grub_printf("Hiperiso grub is not launched by Hiperiso shim.\n\n");
            grub_refresh();

            hiperiso_prompt_end();
        }

        g_hiso_shim->Launched();
    }

    return 0;
}


#endif

static int hiperiso_arch_mode_init(void)
{
    #ifdef GRUB_MACHINE_EFI

    if (grub_strcmp(GRUB_TARGET_CPU, "i386") == 0)
    {
        g_hiperiso_plat_data = HISO_PLAT_I386_UEFI;
        grub_snprintf(g_arch_mode_suffix, sizeof(g_arch_mode_suffix), "%s", "ia32");
    }
    else if (grub_strcmp(GRUB_TARGET_CPU, "arm64") == 0)
    {
        g_hiperiso_plat_data = HISO_PLAT_ARM64_UEFI;
        grub_snprintf(g_arch_mode_suffix, sizeof(g_arch_mode_suffix), "%s", "aa64");
    }
    else if (grub_strcmp(GRUB_TARGET_CPU, "mips64el") == 0)
    {
        g_hiperiso_plat_data = HISO_PLAT_MIPS_UEFI;
        grub_snprintf(g_arch_mode_suffix, sizeof(g_arch_mode_suffix), "%s", "mips");
    }
    else
    {
        g_hiperiso_plat_data = HISO_PLAT_X86_64_UEFI;
        grub_snprintf(g_arch_mode_suffix, sizeof(g_arch_mode_suffix), "%s", "uefi");
    }
#else
    g_hiperiso_plat_data = HISO_PLAT_X86_LEGACY;
    grub_snprintf(g_arch_mode_suffix, sizeof(g_arch_mode_suffix), "%s", "legacy");
#endif

    return 0;
}

static int hiperiso_calc_totalmem(grub_uint64_t addr, grub_uint64_t size, grub_memory_type_t type, void *data)
{
    grub_uint64_t *total_mem = (grub_uint64_t *)data;

    (void)addr;
    (void)type;

    *total_mem += size;

    return 0;
}

static int hiperiso_hwinfo_init(void)
{
    char str[256];
    grub_uint64_t total_mem = 0;

    grub_machine_mmap_iterate(hiperiso_calc_totalmem, &total_mem);

    grub_snprintf(str, sizeof(str), "%ld", (long)(total_mem / HISO_SIZE_1MB));
    hiperiso_env_export("grub_total_ram", str);

#ifdef GRUB_MACHINE_EFI
    hiperiso_get_uefi_version(str, sizeof(str));
    hiperiso_env_export("grub_uefi_version", str);

    hiperiso_get_pi_version(str, sizeof(str));
    hiperiso_env_export("grub_pi_version", str);
#else
    hiperiso_env_export("grub_uefi_version", "NA");
    hiperiso_env_export("grub_pi_version", "NA");
#endif

    return 0;
}

static global_var_cfg g_global_vars[] =
{
    { "gfxmode",            "1024x768",   NULL },
    { hiperiso_left_key,      "5%",         NULL },
    { hiperiso_top_key,       "95%",        NULL },
    { hiperiso_color_key,     "#0000ff",    NULL },
    { NULL,                 NULL,         NULL }
};

static const char * hiperiso_global_var_read_hook(struct grub_env_var *var, const char *val)
{
    int i;

    for (i = 0; g_global_vars[i].name; i++)
    {
        if (grub_strcmp(g_global_vars[i].name, var->name) == 0)
        {
            return g_global_vars[i].value;
        }
    }

    return val;
}

static char * hiperiso_global_var_write_hook(struct grub_env_var *var, const char *val)
{
    int i;

    for (i = 0; g_global_vars[i].name; i++)
    {
        if (grub_strcmp(g_global_vars[i].name, var->name) == 0)
        {
            grub_check_free(g_global_vars[i].value);
            g_global_vars[i].value = grub_strdup(val);
            break;
        }
    }

    return grub_strdup(val);
}

int hiperiso_global_var_init(void)
{
    int i;

    for (i = 0; g_global_vars[i].name; i++)
    {
        g_global_vars[i].value = grub_strdup(g_global_vars[i].defval);
        hiperiso_env_export(g_global_vars[i].name, g_global_vars[i].defval);
        grub_register_variable_hook(g_global_vars[i].name, hiperiso_global_var_read_hook, hiperiso_global_var_write_hook);
    }

    return 0;
}

static ctrl_var_cfg g_ctrl_vars[] =
{
    { "HISO_WIN11_BYPASS_CHECK",  "1" },
    { "HISO_WIN11_BYPASS_NRO",    "1" },
    { "HISO_LINUX_REMOUNT",       "0" },
    { "HISO_SECONDARY_BOOT_MENU", "1" },
    { "HISO_WIN_UEFI_RES_LOCK",   "3" },
    { NULL, "" }
};

static const char * hiperiso_ctrl_var_read_hook(struct grub_env_var *var, const char *val)
{
    int i;

    for (i = 0; g_ctrl_vars[i].name; i++)
    {
        if (grub_strcmp(g_ctrl_vars[i].name, var->name) == 0)
        {
            return g_ctrl_vars[i].szval;
        }
    }

    return val;
}

static char * hiperiso_ctrl_var_write_hook(struct grub_env_var *var, const char *val)
{
    int i;

    for (i = 0; g_ctrl_vars[i].name; i++)
    {
        if (grub_strcmp(g_ctrl_vars[i].name, var->name) == 0)
        {
            if (val && grub_isdigit(val[0]) && val[1] == 0)
            {
                g_ctrl_vars[i].szval[0] = val[0];
                return grub_strdup(val);
            }
            else
            {
                g_ctrl_vars[i].szval[0] = '0';
                return grub_strdup("0");
            }
        }
    }

    return grub_strdup(val);
}

int hiperiso_ctrl_var_init(void)
{
    ctrl_var_cfg *cfg = g_ctrl_vars;

    while (cfg->name)
    {
        hiperiso_env_export(cfg->name, cfg->szval);
        grub_register_variable_hook(cfg->name, hiperiso_ctrl_var_read_hook, hiperiso_ctrl_var_write_hook);
        cfg++;
    }

    return 0;
}

GRUB_MOD_INIT(hiperiso)
{
    hiperiso_hwinfo_init();
    hiperiso_env_init();
    hiperiso_arch_mode_init();

#ifdef GRUB_MACHINE_EFI
    hiperiso_secure_boot_init();
#endif

    hiperiso_register_all_cmd();
}

GRUB_MOD_FINI(hiperiso)
{
    hiperiso_unregister_all_cmd();
}

