-- 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 logging = require 'mc.logging'
local socket = require 'skynet.socket'
require 'skynet.manager'

local listen_id = nil
local agent = nil
local CMD = {}

function CMD.exit()
    socket.shutdown(listen_id)
    skynet.call(agent, 'lua', 'exit')
    skynet.timeout(0, function()
        logging:info('portal service exit')
        skynet.exit()
    end)
end

skynet.start(function()
    skynet.uniqueservice('sd_bus')
    skynet.register('web_backend')

    agent = skynet.newservice('web_backend/service/portal_agent')
    skynet.call(agent, 'lua', 'start_server')

    local listen = skynet.getenv('WEBBACKEND_PORTAL_LISTEN') or '0.0.0.0:8081'
    local ip, port = string.match(listen, '^(%d+.%d+.%d+.%d+):(%d+)$')
    if not ip or not port then
        error('invalid listen address')
    end

    listen_id = socket.listen(ip, tonumber(port))
    logging:info('Listen http port %d', port)
    socket.start(listen_id, function(id, _)
        skynet.send(agent, 'lua', 'open', id)
    end)

    skynet.dispatch('lua', function(_, _, cmd, ...)
        local f = assert(CMD[cmd])
        skynet.ret(skynet.pack(f(...)))
    end)
end)
