#!/usr/bin/python
#
# Copyright Tristan Le Guern (@tleguern) <tleguern at bouledef.eu>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later


DOCUMENTATION = r"""
module: proxmox_storage_info
short_description: Retrieve information about one or more Proxmox VE storages
description:
  - Retrieve information about one or more Proxmox VE storages.
options:
  storage:
    description:
      - Only return information on a specific storage.
    aliases: ['name']
    type: str
  type:
    description:
      - Filter on a specific storage type.
    type: str
author: Tristan Le Guern (@tleguern)
extends_documentation_fragment:
  - community.proxmox.proxmox.actiongroup_proxmox
  - community.proxmox.proxmox.documentation
  - community.proxmox.attributes
  - community.proxmox.attributes.info_module
notes:
  - Storage specific options can be returned by this module, please look at the documentation at U(https://pve.proxmox.com/wiki/Storage).
"""


EXAMPLES = r"""
- name: List existing storages
  community.proxmox.proxmox_storage_info:
  register: proxmox_storages

- name: List NFS storages only
  community.proxmox.proxmox_storage_info:
    type: nfs
  register: proxmox_storages_nfs

- name: Retrieve information about the lvm2 storage
  community.proxmox.proxmox_storage_info:
    storage: lvm2
  register: proxmox_storage_lvm
"""


RETURN = r"""
proxmox_storages:
  description: List of storage pools.
  returned: on success
  type: list
  elements: dict
  contains:
    content:
      description: Proxmox content types available in this storage.
      returned: on success
      type: list
      elements: str
    digest:
      description: Storage's digest.
      returned: on success
      type: str
    nodes:
      description: List of nodes associated to this storage.
      returned: on success, if storage is not local
      type: list
      elements: str
    path:
      description: Physical path to this storage.
      returned: on success
      type: str
    prune-backups:
      description: Backup retention options.
      returned: on success
      type: list
      elements: dict
    shared:
      description: Is this storage shared.
      returned: on success
      type: bool
    storage:
      description: Storage name.
      returned: on success
      type: str
    type:
      description: Storage type.
      returned: on success
      type: str
"""


from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
    ProxmoxAnsible,
    create_proxmox_module,
    proxmox_to_ansible_bool,
)


def module_args():
    return dict(
        storage=dict(type="str", aliases=["name"]),
        type=dict(type="str"),
    )


def module_options():
    return dict(mutually_exclusive=[("storage", "type")])


class ProxmoxStorageInfoAnsible(ProxmoxAnsible):
    def get_storage(self, storage):
        try:
            storage = self.proxmox_api.storage.get(storage)
        except Exception:
            self.module.fail_json(msg=f"Storage '{storage}' does not exist")
        return ProxmoxStorage(storage)

    def get_storages(self, storagetype=None):
        storages = self.proxmox_api.storage.get(type=storagetype)
        storages = [ProxmoxStorage(storage) for storage in storages]
        return storages


class ProxmoxStorage:
    def __init__(self, storage):
        self.storage = storage
        # Convert proxmox representation of lists, dicts and boolean for easier
        # manipulation within ansible.
        if "shared" in self.storage:
            self.storage["shared"] = proxmox_to_ansible_bool(self.storage["shared"])
        if "content" in self.storage:
            self.storage["content"] = self.storage["content"].split(",")
        if "nodes" in self.storage:
            self.storage["nodes"] = self.storage["nodes"].split(",")
        if "prune-backups" in storage:
            options = storage["prune-backups"].split(",")
            self.storage["prune-backups"] = dict()
            for option in options:
                k, v = option.split("=")
                self.storage["prune-backups"][k] = v


def main():
    module = create_proxmox_module(module_args(), **module_options())
    proxmox = ProxmoxStorageInfoAnsible(module)

    result = dict(changed=False)

    storage = module.params["storage"]
    storagetype = module.params["type"]

    if storage:
        storages = [proxmox.get_storage(storage)]
    else:
        storages = proxmox.get_storages(storagetype)
    result["proxmox_storages"] = [storage.storage for storage in storages]

    module.exit_json(**result)


if __name__ == "__main__":
    main()
