#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type


DOCUMENTATION = '''
---
module: xenserver_facts
short_description: get facts reported on xenserver
description:
  - Reads data out of XenAPI, can be used instead of multiple xe commands.
author:
    - Andy Hill (@andyhky)
    - Tim Rupp (@caphrim007)
    - Robin Lee (@cheese)
options: {}
'''

EXAMPLES = '''
- name: Gather facts from xenserver
  community.general.xenserver_facts:

- name: Print running VMs
  ansible.builtin.debug:
    msg: "{{ item }}"
  with_items: "{{ xs_vms.keys() }}"
  when: xs_vms[item]['power_state'] == "Running"

# Which will print:
#
# TASK: [Print running VMs] ***********************************************************
# skipping: [10.13.0.22] => (item=CentOS 4.7 (32-bit))
# ok: [10.13.0.22] => (item=Control domain on host: 10.0.13.22) => {
#     "item": "Control domain on host: 10.0.13.22",
#     "msg": "Control domain on host: 10.0.13.22"
# }
'''


HAVE_XENAPI = False
try:
    import XenAPI
    HAVE_XENAPI = True
except ImportError:
    pass

from ansible.module_utils import distro
from ansible.module_utils.basic import AnsibleModule


class XenServerFacts:
    def __init__(self):
        self.codes = {
            '5.5.0': 'george',
            '5.6.100': 'oxford',
            '6.0.0': 'boston',
            '6.1.0': 'tampa',
            '6.2.0': 'clearwater'
        }

    @property
    def version(self):
        result = distro.linux_distribution()[1]
        return result

    @property
    def codename(self):
        if self.version in self.codes:
            result = self.codes[self.version]
        else:
            result = None

        return result


def get_xenapi_session():
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password('', '')
    return session


def get_networks(session):
    recs = session.xenapi.network.get_all_records()
    networks = change_keys(recs, key='name_label')
    return networks


def get_pifs(session):
    recs = session.xenapi.PIF.get_all_records()
    pifs = change_keys(recs, key='uuid')
    xs_pifs = {}
    devicenums = range(0, 7)
    for pif in pifs.values():
        for eth in devicenums:
            interface_name = "eth%s" % (eth)
            bond_name = interface_name.replace('eth', 'bond')
            if pif['device'] == interface_name:
                xs_pifs[interface_name] = pif
            elif pif['device'] == bond_name:
                xs_pifs[bond_name] = pif
    return xs_pifs


def get_vlans(session):
    recs = session.xenapi.VLAN.get_all_records()
    return change_keys(recs, key='tag')


def change_keys(recs, key='uuid', filter_func=None):
    """
    Take a xapi dict, and make the keys the value of recs[ref][key].

    Preserves the ref in rec['ref']

    """
    new_recs = {}

    for ref, rec in recs.items():
        if filter_func is not None and not filter_func(rec):
            continue

        for param_name, param_value in rec.items():
            # param_value may be of type xmlrpc.client.DateTime,
            # which is not simply convertable to str.
            # Use 'value' attr to get the str value,
            # following an example in xmlrpc.client.DateTime document
            if hasattr(param_value, "value"):
                rec[param_name] = param_value.value
        new_recs[rec[key]] = rec
        new_recs[rec[key]]['ref'] = ref

    return new_recs


def get_host(session):
    """Get the host"""
    host_recs = session.xenapi.host.get_all()
    # We only have one host, so just return its entry
    return session.xenapi.host.get_record(host_recs[0])


def get_vms(session):
    recs = session.xenapi.VM.get_all_records()
    if not recs:
        return None
    vms = change_keys(recs, key='name_label')
    return vms


def get_srs(session):
    recs = session.xenapi.SR.get_all_records()
    if not recs:
        return None
    srs = change_keys(recs, key='name_label')
    return srs


def main():
    module = AnsibleModule(
        supports_check_mode=True,
    )

    if not HAVE_XENAPI:
        module.fail_json(changed=False, msg="python xen api required for this module")

    obj = XenServerFacts()
    try:
        session = get_xenapi_session()
    except XenAPI.Failure as e:
        module.fail_json(msg='%s' % e)

    data = {
        'xenserver_version': obj.version,
        'xenserver_codename': obj.codename
    }

    xs_networks = get_networks(session)
    xs_pifs = get_pifs(session)
    xs_vlans = get_vlans(session)
    xs_vms = get_vms(session)
    xs_srs = get_srs(session)

    if xs_vlans:
        data['xs_vlans'] = xs_vlans
    if xs_pifs:
        data['xs_pifs'] = xs_pifs
    if xs_networks:
        data['xs_networks'] = xs_networks

    if xs_vms:
        data['xs_vms'] = xs_vms

    if xs_srs:
        data['xs_srs'] = xs_srs

    module.exit_json(ansible_facts=data)


if __name__ == '__main__':
    main()

plugins/modules/cloud/misc/xenserver_facts.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type


DOCUMENTATION = '''
---
module: xenserver_facts
short_description: get facts reported on xenserver
description:
  - Reads data out of XenAPI, can be used instead of multiple xe commands.
author:
    - Andy Hill (@andyhky)
    - Tim Rupp (@caphrim007)
    - Robin Lee (@cheese)
options: {}
'''

EXAMPLES = '''
- name: Gather facts from xenserver
  community.general.xenserver_facts:

- name: Print running VMs
  ansible.builtin.debug:
    msg: "{{ item }}"
  with_items: "{{ xs_vms.keys() }}"
  when: xs_vms[item]['power_state'] == "Running"

# Which will print:
#
# TASK: [Print running VMs] ***********************************************************
# skipping: [10.13.0.22] => (item=CentOS 4.7 (32-bit))
# ok: [10.13.0.22] => (item=Control domain on host: 10.0.13.22) => {
#     "item": "Control domain on host: 10.0.13.22",
#     "msg": "Control domain on host: 10.0.13.22"
# }
'''


HAVE_XENAPI = False
try:
    import XenAPI
    HAVE_XENAPI = True
except ImportError:
    pass

from ansible.module_utils import distro
from ansible.module_utils.basic import AnsibleModule


class XenServerFacts:
    def __init__(self):
        self.codes = {
            '5.5.0': 'george',
            '5.6.100': 'oxford',
            '6.0.0': 'boston',
            '6.1.0': 'tampa',
            '6.2.0': 'clearwater'
        }

    @property
    def version(self):
        result = distro.linux_distribution()[1]
        return result

    @property
    def codename(self):
        if self.version in self.codes:
            result = self.codes[self.version]
        else:
            result = None

        return result


def get_xenapi_session():
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password('', '')
    return session


def get_networks(session):
    recs = session.xenapi.network.get_all_records()
    networks = change_keys(recs, key='name_label')
    return networks


def get_pifs(session):
    recs = session.xenapi.PIF.get_all_records()
    pifs = change_keys(recs, key='uuid')
    xs_pifs = {}
    devicenums = range(0, 7)
    for pif in pifs.values():
        for eth in devicenums:
            interface_name = "eth%s" % (eth)
            bond_name = interface_name.replace('eth', 'bond')
            if pif['device'] == interface_name:
                xs_pifs[interface_name] = pif
            elif pif['device'] == bond_name:
                xs_pifs[bond_name] = pif
    return xs_pifs


def get_vlans(session):
    recs = session.xenapi.VLAN.get_all_records()
    return change_keys(recs, key='tag')


def change_keys(recs, key='uuid', filter_func=None):
    """
    Take a xapi dict, and make the keys the value of recs[ref][key].

    Preserves the ref in rec['ref']

    """
    new_recs = {}

    for ref, rec in recs.items():
        if filter_func is not None and not filter_func(rec):
            continue

        for param_name, param_value in rec.items():
            # param_value may be of type xmlrpc.client.DateTime,
            # which is not simply convertable to str.
            # Use 'value' attr to get the str value,
            # following an example in xmlrpc.client.DateTime document
            if hasattr(param_value, "value"):
                rec[param_name] = param_value.value
        new_recs[rec[key]] = rec
        new_recs[rec[key]]['ref'] = ref

    return new_recs


def get_host(session):
    """Get the host"""
    host_recs = session.xenapi.host.get_all()
    # We only have one host, so just return its entry
    return session.xenapi.host.get_record(host_recs[0])


def get_vms(session):
    recs = session.xenapi.VM.get_all_records()
    if not recs:
        return None
    vms = change_keys(recs, key='name_label')
    return vms


def get_srs(session):
    recs = session.xenapi.SR.get_all_records()
    if not recs:
        return None
    srs = change_keys(recs, key='name_label')
    return srs


def main():
    module = AnsibleModule({}, supports_check_mode=True)

    if not HAVE_XENAPI:
        module.fail_json(changed=False, msg="python xen api required for this module")

    obj = XenServerFacts()
    try:
        session = get_xenapi_session()
    except XenAPI.Failure as e:
        module.fail_json(msg='%s' % e)

    data = {
        'xenserver_version': obj.version,
        'xenserver_codename': obj.codename
    }

    xs_networks = get_networks(session)
    xs_pifs = get_pifs(session)
    xs_vlans = get_vlans(session)
    xs_vms = get_vms(session)
    xs_srs = get_srs(session)

    if xs_vlans:
        data['xs_vlans'] = xs_vlans
    if xs_pifs:
        data['xs_pifs'] = xs_pifs
    if xs_networks:
        data['xs_networks'] = xs_networks

    if xs_vms:
        data['xs_vms'] = xs_vms

    if xs_srs:
        data['xs_srs'] = xs_srs

    module.exit_json(ansible_facts=data)


if __name__ == '__main__':
    main()

plugins/modules/cloud/misc/xenserver_facts.py
diff --git a/changelogs/fragments/5383-xenserver_facts.yml b/changelogs/fragments/5383-xenserver_facts.yml
new file mode 100644
index 00000000000..2fee2c87518
--- /dev/null
+++ b/changelogs/fragments/5383-xenserver_facts.yml
@@ -0,0 +1,2 @@
+bugfixes:
+  - "xenserver_facts - fix broken ``AnsibleModule`` call that prevented the module from working at all (https://github.com/ansible-collections/community.general/pull/5383)."
diff --git a/plugins/modules/cloud/misc/xenserver_facts.py b/plugins/modules/cloud/misc/xenserver_facts.py
index f65e3c9a86f..5d336c6f624 100644
--- a/plugins/modules/cloud/misc/xenserver_facts.py
+++ b/plugins/modules/cloud/misc/xenserver_facts.py
@@ -161,9 +161,7 @@ def get_srs(session):
 
 
 def main():
-    module = AnsibleModule(
-        supports_check_mode=True,
-    )
+    module = AnsibleModule({}, supports_check_mode=True)
 
     if not HAVE_XENAPI:
         module.fail_json(changed=False, msg="python xen api required for this module")

community.general.xenserver_facts module error __init__() missing 1 required positional argument: 'argument_spec'
### Summary

When I try to use the [community.general.xenserver_facts module](https://docs.ansible.com/ansible/latest/collections/community/general/xenserver_facts_module.html) I get an error.

### Issue Type

Bug Report

### Component Name

xenserver_facts_module

### Ansible Version

```console (paste below)
$ ansible --version
ansible [core 2.13.4]
  config file = /home/chris/.ansible.cfg
  configured module search path = ['/home/chris/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  ansible collection location = /home/chris/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.10.7 (main, Oct  1 2022, 04:31:04) [GCC 12.2.0]
  jinja version = 3.0.3
  libyaml = True
```


### Community.general Version

```console (paste below)
$ ansible-galaxy collection list community.general

# /home/chris/.ansible/collections/ansible_collections
Collection        Version
----------------- -------
community.general 5.7.0  

# /usr/lib/python3/dist-packages/ansible_collections
Collection        Version
----------------- -------
community.general 5.6.0  
```


### Configuration

```console (paste below)
$ ansible-config dump --only-changed
DEFAULT_TIMEOUT(/home/chris/.ansible.cfg) = 300
```


### OS / Environment

Debian Bookworm

### Steps to Reproduce

<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
- name: Gather Xen facts
  community.general.xenserver_facts:
```


### Expected Results

Something other than an error...

### Actual Results

```console (paste below)
TASK [xen : Gather Xen facts] ********************************************************************************************************
task path: /home/chris/webarch/servers/galaxy/roles/xen/tasks/main.yml:2
redirecting (type: modules) community.general.xenserver_facts to community.general.cloud.misc.xenserver_facts
redirecting (type: modules) community.general.xenserver_facts to community.general.cloud.misc.xenserver_facts
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: TypeError: __init__() missing 1 required positional argument: 'argument_spec'
fatal: [xen4.webarch.net]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"<stdin>\", line 107, in <module>\n  File \"<stdin>\", line 99, in _ansiballz_main\n  File \"<stdin>\", line 47, in invoke_module\n  File \"/usr/lib/python3.9/runpy.py\", line 210, in run_module\n    return _run_module_code(code, init_globals, run_name, mod_spec)\n  File \"/usr/lib/python3.9/runpy.py\", line 97, in _run_module_code\n    _run_code(code, mod_globals, init_globals,\n  File \"/usr/lib/python3.9/runpy.py\", line 87, in _run_code\n    exec(code, run_globals)\n  File \"/tmp/ansible_community.general.xenserver_facts_payload_ilqmvdk8/ansible_community.general.xenserver_facts_payload.zip/ansible_collections/community/general/plugins/modules/cloud/misc/xenserver_facts.py\", line 206, in <module>\n  File \"/tmp/ansible_community.general.xenserver_facts_payload_ilqmvdk8/ansible_community.general.xenserver_facts_payload.zip/ansible_collections/community/general/plugins/modules/cloud/misc/xenserver_facts.py\", line 165, in main\nTypeError: __init__() missing 1 required positional argument: 'argument_spec'\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```


### Code of Conduct

- [X] I agree to follow the Ansible Code of Conduct
