-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local skynet = require('skynet')
local sd_bus = require('sd_bus')
local log = require('mc.logging')
local utils = require('mc.utils')
local mdb = require('mc.mdb')
local ctx = require('mc.context')
local test_common = require('test_common.utils')
local test_ipmi = require('test_ipmi')
require('skynet.manager')
local test_storage_common = require('test_storage_common')
local test_subhealth = require('test_subhealth')
local test_rpc_extra = require('test_rpc_extra')
local SERVICE_STORAGE <const> = 'bmc.kepler.storage'
local SERVICE_CONTROLLER <const> = 'bmc.kepler.Systems.Storage.Controller'
local DRIVE_PATH <const> = '/bmc/kepler/Systems/1/Storage/Drives/Drive_9_010102'
local DRIVE_INTF <const> = 'bmc.kepler.Systems.Storage.Drive.NVMe'
require('storage.json_types.NVMe')

local function prepare_test_data()
    local project_dir = os.getenv('PROJECT_DIR')
    local test_dir = project_dir .. '/test/integration/.test_temp_data/'
    skynet.setenv('PROG_APP_PATH', test_dir .. 'apps')
    skynet.setenv('PROG_CSR_PATH', test_dir .. 'sr')
    skynet.setenv('DATA_CSR_PATH', test_dir .. 'data/sr')
    local test_data_dir = skynet.getenv('TEST_DATA_DIR')
    os.execute('mkdir -p ' .. test_data_dir)
    utils.copy_file('test/integration/data/passwd', test_data_dir .. '/passwd')
    utils.copy_file('test/integration/data/shadow', test_data_dir .. '/shadow')
    utils.copy_file('test/integration/data/group', test_data_dir .. '/group')
    utils.copy_file('test/integration/data/datatocheck_default.dat', test_data_dir .. '/datatocheck_default.dat')
    os.execute('mkdir -p ' .. test_data_dir .. 'usr/lib64')
    utils.copy_file('temp/usr/lib64/mock/libsoc_adapter_it.so', test_data_dir .. 'usr/lib64/libsoc_adapter.so')
    local dir_list = { 'apps/storage/mds', 'apps/hwdiscovery/mds', 'apps/fructrl/mds', 'apps/ipmi_core/mds', 'sr' }
    for _, path in pairs(dir_list) do
        os.execute('mkdir -p ' .. test_data_dir .. '/' .. path)
    end
    utils.copy_file(
        'test/integration/test_data/14140130_19e53758_19e50185.sr',
        test_data_dir .. '/sr/14140130_19e53758_19e50185.sr'
    )
    utils.copy_file(
        'test/integration/test_data/14100513_IEU_040302023940.sr',
        test_data_dir .. '/sr/14100513_IEU_040302023940.sr'
    )
    utils.copy_file('test/integration/test_data/14100513_BCU_01.sr', test_data_dir .. '/sr/14100513_BCU_01.sr')
    utils.copy_file('test/integration/test_data/1406G002_SEU_01.sr', test_data_dir .. '/sr/1406G002_SEU_01.sr')
    utils.copy_file('test/integration/test_data/14100513_EXU_01.sr', test_data_dir .. '/sr/14100513_EXU_01.sr')
    utils.copy_file('test/integration/test_data/root.sr', test_data_dir .. '/sr/root.sr')
    utils.copy_file('test/integration/test_data/platform.sr', test_data_dir .. '/sr/platform.sr')
    utils.copy_file('mds/schema.json', test_data_dir .. '/apps/storage/mds/schema.json')
    utils.copy_file(
        'temp/opt/bmc/apps/hwdiscovery/mds/schema.json',
        test_data_dir .. '/apps/hwdiscovery/mds/schema.json'
    )
    utils.copy_file('temp/opt/bmc/apps/fructrl/mds/schema.json', test_data_dir .. '/apps/fructrl/mds/schema.json')
    utils.copy_file('temp/opt/bmc/apps/ipmi_core/mds/schema.json', test_data_dir .. '/apps/ipmi_core/mds/schema.json')

    local temp_dir = os.getenv('PROJECT_DIR') .. '/temp'
    os.execute(
        string.format(
            'find %s -name client.lua|xargs sed -i -e \'s/local MAX_RETRY_TIMES<const> ='
                .. ' 10/local MAX_RETRY_TIMES<const> = 1/g\'',
            temp_dir
        )
    )
end

local function clear_test_data(exit_test)
    log:info('clear test data')
    local test_data_dir = skynet.getenv('TEST_DATA_DIR')
    if exit_test then
        skynet.timeout(0, function()
            skynet.sleep(20)
            skynet.abort()
            utils.remove_file(test_data_dir)
        end)
    else
        utils.remove_file(test_data_dir)
    end
end

local function get_controller_properties(bus, controller_path, prop_name)
    return bus
        :call(SERVICE_STORAGE, controller_path, 'org.freedesktop.DBus.Properties', 'GetAll', 's', SERVICE_CONTROLLER)[prop_name]
        :value()
end

local function test_controller_on_resource_tree(bus)
    log:notice('================ start test_controller_on_resource_tree ================')
    -- mock 环境无 RAID 控制器数据,Controller 对象不会上树,此处容错处理
    local ok, name = pcall(function()
        return get_controller_properties(
            bus,
            '/bmc/kepler/Systems/1/Storage/Controllers/Controller_1_0101010101',
            'Name'
        )
    end)
    if ok then
        log:notice('The name of controller is ' .. name)
    else
        log:notice('skip test_controller_on_resource_tree, controller not available: %s', tostring(name))
    end
    log:notice('================ finish test_controller_on_resource_tree ================')
end

local function test_get_smart_info_method(bus)
    local obj = mdb.get_object(bus, DRIVE_PATH, DRIVE_INTF)
    local _, err = pcall(function()
        obj:GetSmartInfo(ctx.new(), 0)
    end)
    assert(err.name == 'ActionNotSupported')
end

local function test_send_nvmemi_command_method(bus)
    local obj = mdb.get_object(bus, DRIVE_PATH, DRIVE_INTF)
    local _, err = pcall(function()
        obj:SendNvmeMICommand(ctx.new(), 4, 3, 0, { 2, 3 })
    end)
    assert(err.name == 'ActionNotSupported')
end

local function test_get_identify_data_method(bus)
    local obj = mdb.get_object(bus, DRIVE_PATH, DRIVE_INTF)
    local _, err = pcall(function()
        obj:GetIdentifyData(ctx.new(), 0)
    end)
    assert(err.name == 'ActionNotSupported')
end

local function test_get_telemetry_data_method(bus)
    local obj = mdb.get_object(bus, DRIVE_PATH, DRIVE_INTF)
    local _, err = pcall(function()
        obj:GetTelemetryData(ctx.new(), 'Host')
    end)
    assert(err.name == 'ActionNotSupported')
end

-- 等待 Drive 对象注册到 mdb 总线(方法调用返回 ActionNotSupported 视为对象已可路由)。
-- storage 服务处理 hwdiscovery 数据上树 Drive 对象是异步的,直接调用可能命中注册完成前的空窗。
local function wait_drive_object_ready(bus)
    local last_err
    for _ = 1, 400 do
        local ok_get, obj = pcall(mdb.get_object, bus, DRIVE_PATH, DRIVE_INTF)
        if ok_get then
            local _, err = pcall(function()
                obj:GetSmartInfo(ctx.new(), 0)
            end)
            last_err = err
            if type(err) == 'table' and err.name == 'ActionNotSupported' then
                return
            end
        else
            last_err = obj
        end
        skynet.sleep(10)
    end
    error(string.format('wait drive object ready timeout, err=%s', tostring(last_err)))
end

local function test_nvme_rpc(bus)
    -- 测试方法是否上树
    log:notice('================ start test_drive_on_resource_tree ================')
    wait_drive_object_ready(bus)
    test_get_smart_info_method(bus)
    test_send_nvmemi_command_method(bus)
    test_get_identify_data_method(bus)
    test_get_telemetry_data_method(bus)
    log:notice('================ finish test_drive_on_resource_tree ================')
end

local function test_ipmi_func()
    log:notice('================ start test_ipmi_func ================')
    test_ipmi.get_hdd_pwr_status()
    test_ipmi.get_controller_list()
    test_ipmi.get_controller_fw_version()
    test_ipmi.get_controller_nvdata_version()
    test_ipmi.get_controller_info()
    test_ipmi.get_logical_drive_list()
    test_ipmi.get_controller_pds()
    test_ipmi.get_physical_drive_location()
    test_ipmi.get_physical_drive_info()
    test_ipmi.get_physical_drive_led_status()
    test_ipmi.get_array_list()
    test_ipmi.get_array_lds()
    test_ipmi.get_array_pds()
    test_ipmi.get_logical_drive_list_ex()
    test_ipmi.get_array_lds_ex()
    test_ipmi.create_logical_drive_on_new_array()
    test_ipmi.create_logical_drive_on_existed_array()
    test_ipmi.delete_logical_drive()
    test_ipmi.set_logic_drive_rp()
    test_ipmi.set_logic_drive_wp()
    test_ipmi.set_logic_drive_bootable()
    test_ipmi.set_controller_copyback()
    test_ipmi.set_controller_smarter_copyback()
    test_ipmi.set_controller_restore_settings()
    test_ipmi.set_controller_jbod()
    test_ipmi.set_location_indicator_state()
    test_ipmi.set_firmware_status()
    test_ipmi.set_hotspare_type()
    test_ipmi.set_controller_outofband()
    test_ipmi.set_raid_fault_status()
    test_ipmi.set_pd_log_collect()
    test_ipmi.set_fault_indicator_state()
    log:notice('================ end test_ipmi_func ================')
end

local function test_storage()
    log:notice('================ test storage start ================')
    local bus = sd_bus.open_user(true)
    test_storage_common.set_bus(bus)

    local ok, err = pcall(function()
        test_ipmi_func()
        -- the functions to be test
        test_controller_on_resource_tree(bus)
        test_subhealth.io_deterioration_test(bus)
    end)
    if not ok then
        log:error('=== ipmi/controller/subhealth test failed ===: %s', err)
    end
    test_nvme_rpc(bus)
    test_rpc_extra.main(bus)
    log:notice('================ test storage complete ================')
end

skynet.start(function()
    clear_test_data()
    prepare_test_data()
    test_common.dbus_launch()
    skynet.uniqueservice('sd_bus')
    skynet.uniqueservice('persistence/service/main')
    skynet.uniqueservice('maca/service/main')
    skynet.uniqueservice('hwdiscovery/service/main')
    skynet.uniqueservice('ipmi_core/service/main')
    skynet.uniqueservice('fructrl/service/main')
    -- 提供 HddBackPlanes.DriveSlotAllocationStatus,避免 Drive 对象等待超时阻塞上树
    skynet.uniqueservice('mock_service/mock_hdd_backplanes')
    skynet.uniqueservice('main')
    skynet.sleep(500)
    skynet.fork(function()
        local ok, err = pcall(test_storage)
        clear_test_data(true)
        if not ok then
            log:error('=== test failed ===: %s', err)
        end
    end)
end)