#!/usr/bin/python3
#
# This file is part of OpenMediaVault.
#
# @license   http://www.gnu.org/licenses/gpl.html GPL Version 3
# @author    Volker Theile <volker.theile@openmediavault.org>
# @copyright Copyright (c) 2009-2025 Volker Theile
#
# OpenMediaVault 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
# any later version.
#
# OpenMediaVault 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 OpenMediaVault. If not, see <http://www.gnu.org/licenses/>.
import os
import sys

import dialog
import natsort
import openmediavault.firstaid
import openmediavault.log
import openmediavault.productinfo

import openmediavault


def load_modules():
    modules = []
    path = openmediavault.getenv(
        "OMV_FIRSTAID_MODULES_DIR",
        "/usr/share/openmediavault/firstaid/modules.d"
    )
    sys.path.insert(0, path)
    for name in natsort.humansorted(os.listdir(path)):
        modname, ext = os.path.splitext(name)
        if not ext == ".py":
            continue
        mod = __import__(modname)
        modinst = mod.Module()
        if not isinstance(modinst, openmediavault.firstaid.IModule):
            continue
        modules.append(modinst)
    sys.path.pop(0)
    return modules


def main():
    rc = 1  # lgtm[py/multiple-definition]
    pi = openmediavault.productinfo.ProductInfo()
    # Load the modules.
    modules = load_modules()
    # Fill the menu choices.
    choices = []
    for idx, module in enumerate(modules):
        choices.append([str(idx + 1), module.description])
    # Show the available modules.
    d = dialog.Dialog(dialog="dialog")
    while 1:
        (code, tag) = d.menu(
            "Please select a menu.",
            title="First aid",
            cancel_label="Exit",
            clear=True,
            backtitle="{} - {}".format(pi.name, pi.copyright),
            height=17,
            width=65,
            menu_height=10,
            choices=choices
        )
        if code in (d.CANCEL, d.ESC):
            rc = 0
            break
        elif code == d.OK:
            d.clear()
            module = modules[int(tag) - 1]
            try:
                rc = module.execute()
            except Exception as e:  # pylint: disable=broad-except
                rc = 1
                openmediavault.log.error(str(e))
            break
    return rc


if __name__ == "__main__":
    sys.exit(main())
