We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
gconftool2 throws an IndexError exception when setting configuration
### Summary

When setting a key using gconftool2, an IndexError exception is thrown because the wrong index is used when formatting the command string. It appears to have been broken since version 4.8.1 of this collection. It should be a simple one character fix and would be great if we could have it back ported as a patch for the older releases.

Effectively 
`cmd.extend(["--type", self.value_type, "--{3}".format(call_type), self.key, self.value])`
Should be
`cmd.extend(["--type", self.value_type, "--{0}".format(call_type), self.key, self.value])`

### Issue Type

Bug Report

### Component Name

gconftool2

### Ansible Version

```console (paste below)
$ ansible --version
ansible [core 2.13.5]
  config file = /Users/***/work/ansible/ansible.cfg
  configured module search path = ['/Users/***/work/ansible/library']
  ansible python module location = /Users/***/Library/Python/3.9/lib/python/site-packages/ansible
  ansible collection location = /Users/***/.ansible/collections:/usr/share/ansible/collections
  executable location = /Users/***/Library/Python/3.9/bin/ansible
  python version = 3.9.6 (default, Sep 26 2022, 11:37:49) [Clang 14.0.0 (clang-1400.0.29.202)]
  jinja version = 3.1.2
  libyaml = True
```


### Community.general Version

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


### Configuration

```yaml (paste below)
- community.general.gconftool2:
    key: '/desktop/gnome/remote_access/enabled'
    value_type: 'bool'
    value: 'true'
    state: 'present'
```


### OS / Environment

Targeting CentOS 7.9

### Steps to Reproduce

<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)

```


### Expected Results

I expect  gconftool2 to set the key and not throw an exception

### Actual Results

```console (paste below)
Traceback (most recent call last):
  File \"/home/***/.ansible/tmp/ansible-tmp-1669197386.99966-48716-109362476478706/AnsiballZ_gconftool2.py\", line 107, in <module>
    _ansiballz_main()
  File \"/home/***/.ansible/tmp/ansible-tmp-1669197386.99966-48716-109362476478706/AnsiballZ_gconftool2.py\", line 99, in _ansiballz_main
    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
  File \"/home/***/.ansible/tmp/ansible-tmp-1669197386.99966-48716-109362476478706/AnsiballZ_gconftool2.py\", line 48, in invoke_module
    run_name='__main__', alter_sys=True)
  File \"/usr/lib64/python2.7/runpy.py\", line 176, in run_module
    fname, loader, pkg_name)
  File \"/usr/lib64/python2.7/runpy.py\", line 82, in _run_module_code
    mod_name, mod_fname, mod_loader, pkg_name)
  File \"/usr/lib64/python2.7/runpy.py\", line 72, in _run_code
    exec code in run_globals
  File \"/tmp/ansible_community.general.gconftool2_payload__SXOuh/ansible_community.general.gconftool2_payload.zip/ansible_collections/community/general/plugins/modules/system/gconftool2.py\", line 230, in <module>
  File \"/tmp/ansible_community.general.gconftool2_payload__SXOuh/ansible_community.general.gconftool2_payload.zip/ansible_collections/community/general/plugins/modules/system/gconftool2.py\", line 213, in main
  File \"/tmp/ansible_community.general.gconftool2_payload__SXOuh/ansible_community.general.gconftool2_payload.zip/ansible_collections/community/general/plugins/modules/system/gconftool2.py\", line 128, in call
  IndexError: tuple index out of range
```


### Code of Conduct

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

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `plugins/modules/system/gconftool2.py`
Content:
```
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 
4 # Copyright (c) 2016, Kenneth D. Evensen <kevensen@redhat.com>
5 # Copyright (c) 2017, Abhijeet Kasurde <akasurde@redhat.com>
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8 
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11 
12 DOCUMENTATION = '''
13 module: gconftool2
14 author:
15     - Kenneth D. Evensen (@kevensen)
16 short_description: Edit GNOME Configurations
17 description:
18   - This module allows for the manipulation of GNOME 2 Configuration via
19     gconftool-2.  Please see the gconftool-2(1) man pages for more details.
20 options:
21   key:
22     type: str
23     description:
24     - A GConf preference key is an element in the GConf repository
25       that corresponds to an application preference. See man gconftool-2(1)
26     required: true
27   value:
28     type: str
29     description:
30     - Preference keys typically have simple values such as strings,
31       integers, or lists of strings and integers. This is ignored if the state
32       is "get". See man gconftool-2(1)
33   value_type:
34     type: str
35     description:
36     - The type of value being set. This is ignored if the state is "get".
37     choices: [ bool, float, int, string ]
38   state:
39     type: str
40     description:
41     - The action to take upon the key/value.
42     required: true
43     choices: [ absent, get, present ]
44   config_source:
45     type: str
46     description:
47     - Specify a configuration source to use rather than the default path.
48       See man gconftool-2(1)
49   direct:
50     description:
51     - Access the config database directly, bypassing server.  If direct is
52       specified then the config_source must be specified as well.
53       See man gconftool-2(1)
54     type: bool
55     default: false
56 '''
57 
58 EXAMPLES = """
59 - name: Change the widget font to "Serif 12"
60   community.general.gconftool2:
61     key: "/desktop/gnome/interface/font_name"
62     value_type: "string"
63     value: "Serif 12"
64 """
65 
66 RETURN = '''
67   key:
68     description: The key specified in the module parameters
69     returned: success
70     type: str
71     sample: /desktop/gnome/interface/font_name
72   value_type:
73     description: The type of the value that was changed
74     returned: success
75     type: str
76     sample: string
77   value:
78     description: The value of the preference key after executing the module
79     returned: success
80     type: str
81     sample: "Serif 12"
82 ...
83 '''
84 
85 from ansible.module_utils.basic import AnsibleModule
86 
87 
88 class GConf2Preference(object):
89     def __init__(self, ansible, key, value_type, value,
90                  direct=False, config_source=""):
91         self.ansible = ansible
92         self.key = key
93         self.value_type = value_type
94         self.value = value
95         self.config_source = config_source
96         self.direct = direct
97 
98     def value_already_set(self):
99         return False
100 
101     def call(self, call_type, fail_onerr=True):
102         """ Helper function to perform gconftool-2 operations """
103         config_source = []
104         direct = []
105         changed = False
106         out = ''
107 
108         # If the configuration source is different from the default, create
109         # the argument
110         if self.config_source is not None and len(self.config_source) > 0:
111             config_source = ["--config-source", self.config_source]
112 
113         # If direct is true, create the argument
114         if self.direct:
115             direct = ["--direct"]
116 
117         # Execute the call
118         cmd = ["gconftool-2"]
119         try:
120             # If the call is "get", then we don't need as many parameters and
121             # we can ignore some
122             if call_type == 'get':
123                 cmd.extend(["--get", self.key])
124             # Otherwise, we will use all relevant parameters
125             elif call_type == 'set':
126                 cmd.extend(direct)
127                 cmd.extend(config_source)
128                 cmd.extend(["--type", self.value_type, "--{3}".format(call_type), self.key, self.value])
129             elif call_type == 'unset':
130                 cmd.extend(["--unset", self.key])
131 
132             # Start external command
133             rc, out, err = self.ansible.run_command(cmd)
134 
135             if err and fail_onerr:
136                 self.ansible.fail_json(msg='gconftool-2 failed with '
137                                            'error: %s' % (str(err)))
138             else:
139                 changed = True
140 
141         except OSError as exception:
142             self.ansible.fail_json(msg='gconftool-2 failed with exception: '
143                                        '%s' % exception)
144         return changed, out.rstrip()
145 
146 
147 def main():
148     # Setup the Ansible module
149     module = AnsibleModule(
150         argument_spec=dict(
151             key=dict(type='str', required=True, no_log=False),
152             value_type=dict(type='str', choices=['bool', 'float', 'int', 'string']),
153             value=dict(type='str'),
154             state=dict(type='str', required=True, choices=['absent', 'get', 'present']),
155             direct=dict(type='bool', default=False),
156             config_source=dict(type='str'),
157         ),
158         supports_check_mode=True
159     )
160 
161     state_values = {"present": "set", "absent": "unset", "get": "get"}
162 
163     # Assign module values to dictionary values
164     key = module.params['key']
165     value_type = module.params['value_type']
166     if module.params['value'].lower() == "true":
167         value = "true"
168     elif module.params['value'] == "false":
169         value = "false"
170     else:
171         value = module.params['value']
172 
173     state = state_values[module.params['state']]
174     direct = module.params['direct']
175     config_source = module.params['config_source']
176 
177     # Initialize some variables for later
178     change = False
179     new_value = ''
180 
181     if state != "get":
182         if value is None or value == "":
183             module.fail_json(msg='State %s requires "value" to be set'
184                                  % str(state))
185         elif value_type is None or value_type == "":
186             module.fail_json(msg='State %s requires "value_type" to be set'
187                                  % str(state))
188 
189         if direct and config_source is None:
190             module.fail_json(msg='If "direct" is "true" then the ' +
191                                  '"config_source" must be specified')
192         elif not direct and config_source is not None:
193             module.fail_json(msg='If the "config_source" is specified ' +
194                                  'then "direct" must be "true"')
195 
196     # Create a gconf2 preference
197     gconf_pref = GConf2Preference(module, key, value_type,
198                                   value, direct, config_source)
199     # Now we get the current value, if not found don't fail
200     dummy, current_value = gconf_pref.call("get", fail_onerr=False)
201 
202     # Check if the current value equals the value we want to set.  If not, make
203     # a change
204     if current_value != value:
205         # If check mode, we know a change would have occurred.
206         if module.check_mode:
207             # So we will set the change to True
208             change = True
209             # And set the new_value to the value that would have been set
210             new_value = value
211         # If not check mode make the change.
212         else:
213             change, new_value = gconf_pref.call(state)
214     # If the value we want to set is the same as the current_value, we will
215     # set the new_value to the current_value for reporting
216     else:
217         new_value = current_value
218 
219     facts = dict(gconftool2={'changed': change,
220                              'key': key,
221                              'value_type': value_type,
222                              'new_value': new_value,
223                              'previous_value': current_value,
224                              'playbook_value': module.params['value']})
225 
226     module.exit_json(changed=change, ansible_facts=facts)
227 
228 
229 if __name__ == '__main__':
230     main()
231
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/plugins/modules/system/gconftool2.py b/plugins/modules/system/gconftool2.py
--- a/plugins/modules/system/gconftool2.py
+++ b/plugins/modules/system/gconftool2.py
@@ -125,7 +125,7 @@
             elif call_type == 'set':
                 cmd.extend(direct)
                 cmd.extend(config_source)
-                cmd.extend(["--type", self.value_type, "--{3}".format(call_type), self.key, self.value])
+                cmd.extend(["--type", self.value_type, "--{0}".format(call_type), self.key, self.value])
             elif call_type == 'unset':
                 cmd.extend(["--unset", self.key])

{"golden_diff": "diff --git a/plugins/modules/system/gconftool2.py b/plugins/modules/system/gconftool2.py\n--- a/plugins/modules/system/gconftool2.py\n+++ b/plugins/modules/system/gconftool2.py\n@@ -125,7 +125,7 @@\n             elif call_type == 'set':\n                 cmd.extend(direct)\n                 cmd.extend(config_source)\n-                cmd.extend([\"--type\", self.value_type, \"--{3}\".format(call_type), self.key, self.value])\n+                cmd.extend([\"--type\", self.value_type, \"--{0}\".format(call_type), self.key, self.value])\n             elif call_type == 'unset':\n                 cmd.extend([\"--unset\", self.key])\n", "issue": "gconftool2 throws an IndexError exception when setting configuration\n### Summary\n\nWhen setting a key using gconftool2, an IndexError exception is thrown because the wrong index is used when formatting the command string. It appears to have been broken since version 4.8.1 of this collection. It should be a simple one character fix and would be great if we could have it back ported as a patch for the older releases.\r\n\r\nEffectively \r\n`cmd.extend([\"--type\", self.value_type, \"--{3}\".format(call_type), self.key, self.value])`\r\nShould be\r\n`cmd.extend([\"--type\", self.value_type, \"--{0}\".format(call_type), self.key, self.value])`\n\n### Issue Type\n\nBug Report\n\n### Component Name\n\ngconftool2\n\n### Ansible Version\n\n```console (paste below)\r\n$ ansible --version\r\nansible [core 2.13.5]\r\n  config file = /Users/***/work/ansible/ansible.cfg\r\n  configured module search path = ['/Users/***/work/ansible/library']\r\n  ansible python module location = /Users/***/Library/Python/3.9/lib/python/site-packages/ansible\r\n  ansible collection location = /Users/***/.ansible/collections:/usr/share/ansible/collections\r\n  executable location = /Users/***/Library/Python/3.9/bin/ansible\r\n  python version = 3.9.6 (default, Sep 26 2022, 11:37:49) [Clang 14.0.0 (clang-1400.0.29.202)]\r\n  jinja version = 3.1.2\r\n  libyaml = True\r\n```\r\n\n\n### Community.general Version\n\n```console (paste below)\r\n$ ansible-galaxy collection list community.general\r\nCollection        Version\r\n----------------- -------\r\ncommunity.general 5.7.0 \r\n```\r\n\n\n### Configuration\n\n```yaml (paste below)\r\n- community.general.gconftool2:\r\n    key: '/desktop/gnome/remote_access/enabled'\r\n    value_type: 'bool'\r\n    value: 'true'\r\n    state: 'present'\r\n```\r\n\n\n### OS / Environment\n\nTargeting CentOS 7.9\n\n### Steps to Reproduce\n\n<!--- Paste example playbooks or commands between quotes below -->\r\n```yaml (paste below)\r\n\r\n```\r\n\n\n### Expected Results\n\nI expect  gconftool2 to set the key and not throw an exception\n\n### Actual Results\n\n```console (paste below)\r\nTraceback (most recent call last):\r\n  File \\\"/home/***/.ansible/tmp/ansible-tmp-1669197386.99966-48716-109362476478706/AnsiballZ_gconftool2.py\\\", line 107, in <module>\r\n    _ansiballz_main()\r\n  File \\\"/home/***/.ansible/tmp/ansible-tmp-1669197386.99966-48716-109362476478706/AnsiballZ_gconftool2.py\\\", line 99, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \\\"/home/***/.ansible/tmp/ansible-tmp-1669197386.99966-48716-109362476478706/AnsiballZ_gconftool2.py\\\", line 48, in invoke_module\r\n    run_name='__main__', alter_sys=True)\r\n  File \\\"/usr/lib64/python2.7/runpy.py\\\", line 176, in run_module\r\n    fname, loader, pkg_name)\r\n  File \\\"/usr/lib64/python2.7/runpy.py\\\", line 82, in _run_module_code\r\n    mod_name, mod_fname, mod_loader, pkg_name)\r\n  File \\\"/usr/lib64/python2.7/runpy.py\\\", line 72, in _run_code\r\n    exec code in run_globals\r\n  File \\\"/tmp/ansible_community.general.gconftool2_payload__SXOuh/ansible_community.general.gconftool2_payload.zip/ansible_collections/community/general/plugins/modules/system/gconftool2.py\\\", line 230, in <module>\r\n  File \\\"/tmp/ansible_community.general.gconftool2_payload__SXOuh/ansible_community.general.gconftool2_payload.zip/ansible_collections/community/general/plugins/modules/system/gconftool2.py\\\", line 213, in main\r\n  File \\\"/tmp/ansible_community.general.gconftool2_payload__SXOuh/ansible_community.general.gconftool2_payload.zip/ansible_collections/community/general/plugins/modules/system/gconftool2.py\\\", line 128, in call\r\n  IndexError: tuple index out of range\r\n```\r\n\n\n### Code of Conduct\n\n- [X] I agree to follow the Ansible Code of Conduct\n", "before_files": [{"content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2016, Kenneth D. Evensen <kevensen@redhat.com>\n# Copyright (c) 2017, Abhijeet Kasurde <akasurde@redhat.com>\n# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)\n# SPDX-License-Identifier: GPL-3.0-or-later\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nDOCUMENTATION = '''\nmodule: gconftool2\nauthor:\n    - Kenneth D. Evensen (@kevensen)\nshort_description: Edit GNOME Configurations\ndescription:\n  - This module allows for the manipulation of GNOME 2 Configuration via\n    gconftool-2.  Please see the gconftool-2(1) man pages for more details.\noptions:\n  key:\n    type: str\n    description:\n    - A GConf preference key is an element in the GConf repository\n      that corresponds to an application preference. See man gconftool-2(1)\n    required: true\n  value:\n    type: str\n    description:\n    - Preference keys typically have simple values such as strings,\n      integers, or lists of strings and integers. This is ignored if the state\n      is \"get\". See man gconftool-2(1)\n  value_type:\n    type: str\n    description:\n    - The type of value being set. This is ignored if the state is \"get\".\n    choices: [ bool, float, int, string ]\n  state:\n    type: str\n    description:\n    - The action to take upon the key/value.\n    required: true\n    choices: [ absent, get, present ]\n  config_source:\n    type: str\n    description:\n    - Specify a configuration source to use rather than the default path.\n      See man gconftool-2(1)\n  direct:\n    description:\n    - Access the config database directly, bypassing server.  If direct is\n      specified then the config_source must be specified as well.\n      See man gconftool-2(1)\n    type: bool\n    default: false\n'''\n\nEXAMPLES = \"\"\"\n- name: Change the widget font to \"Serif 12\"\n  community.general.gconftool2:\n    key: \"/desktop/gnome/interface/font_name\"\n    value_type: \"string\"\n    value: \"Serif 12\"\n\"\"\"\n\nRETURN = '''\n  key:\n    description: The key specified in the module parameters\n    returned: success\n    type: str\n    sample: /desktop/gnome/interface/font_name\n  value_type:\n    description: The type of the value that was changed\n    returned: success\n    type: str\n    sample: string\n  value:\n    description: The value of the preference key after executing the module\n    returned: success\n    type: str\n    sample: \"Serif 12\"\n...\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\n\n\nclass GConf2Preference(object):\n    def __init__(self, ansible, key, value_type, value,\n                 direct=False, config_source=\"\"):\n        self.ansible = ansible\n        self.key = key\n        self.value_type = value_type\n        self.value = value\n        self.config_source = config_source\n        self.direct = direct\n\n    def value_already_set(self):\n        return False\n\n    def call(self, call_type, fail_onerr=True):\n        \"\"\" Helper function to perform gconftool-2 operations \"\"\"\n        config_source = []\n        direct = []\n        changed = False\n        out = ''\n\n        # If the configuration source is different from the default, create\n        # the argument\n        if self.config_source is not None and len(self.config_source) > 0:\n            config_source = [\"--config-source\", self.config_source]\n\n        # If direct is true, create the argument\n        if self.direct:\n            direct = [\"--direct\"]\n\n        # Execute the call\n        cmd = [\"gconftool-2\"]\n        try:\n            # If the call is \"get\", then we don't need as many parameters and\n            # we can ignore some\n            if call_type == 'get':\n                cmd.extend([\"--get\", self.key])\n            # Otherwise, we will use all relevant parameters\n            elif call_type == 'set':\n                cmd.extend(direct)\n                cmd.extend(config_source)\n                cmd.extend([\"--type\", self.value_type, \"--{3}\".format(call_type), self.key, self.value])\n            elif call_type == 'unset':\n                cmd.extend([\"--unset\", self.key])\n\n            # Start external command\n            rc, out, err = self.ansible.run_command(cmd)\n\n            if err and fail_onerr:\n                self.ansible.fail_json(msg='gconftool-2 failed with '\n                                           'error: %s' % (str(err)))\n            else:\n                changed = True\n\n        except OSError as exception:\n            self.ansible.fail_json(msg='gconftool-2 failed with exception: '\n                                       '%s' % exception)\n        return changed, out.rstrip()\n\n\ndef main():\n    # Setup the Ansible module\n    module = AnsibleModule(\n        argument_spec=dict(\n            key=dict(type='str', required=True, no_log=False),\n            value_type=dict(type='str', choices=['bool', 'float', 'int', 'string']),\n            value=dict(type='str'),\n            state=dict(type='str', required=True, choices=['absent', 'get', 'present']),\n            direct=dict(type='bool', default=False),\n            config_source=dict(type='str'),\n        ),\n        supports_check_mode=True\n    )\n\n    state_values = {\"present\": \"set\", \"absent\": \"unset\", \"get\": \"get\"}\n\n    # Assign module values to dictionary values\n    key = module.params['key']\n    value_type = module.params['value_type']\n    if module.params['value'].lower() == \"true\":\n        value = \"true\"\n    elif module.params['value'] == \"false\":\n        value = \"false\"\n    else:\n        value = module.params['value']\n\n    state = state_values[module.params['state']]\n    direct = module.params['direct']\n    config_source = module.params['config_source']\n\n    # Initialize some variables for later\n    change = False\n    new_value = ''\n\n    if state != \"get\":\n        if value is None or value == \"\":\n            module.fail_json(msg='State %s requires \"value\" to be set'\n                                 % str(state))\n        elif value_type is None or value_type == \"\":\n            module.fail_json(msg='State %s requires \"value_type\" to be set'\n                                 % str(state))\n\n        if direct and config_source is None:\n            module.fail_json(msg='If \"direct\" is \"true\" then the ' +\n                                 '\"config_source\" must be specified')\n        elif not direct and config_source is not None:\n            module.fail_json(msg='If the \"config_source\" is specified ' +\n                                 'then \"direct\" must be \"true\"')\n\n    # Create a gconf2 preference\n    gconf_pref = GConf2Preference(module, key, value_type,\n                                  value, direct, config_source)\n    # Now we get the current value, if not found don't fail\n    dummy, current_value = gconf_pref.call(\"get\", fail_onerr=False)\n\n    # Check if the current value equals the value we want to set.  If not, make\n    # a change\n    if current_value != value:\n        # If check mode, we know a change would have occurred.\n        if module.check_mode:\n            # So we will set the change to True\n            change = True\n            # And set the new_value to the value that would have been set\n            new_value = value\n        # If not check mode make the change.\n        else:\n            change, new_value = gconf_pref.call(state)\n    # If the value we want to set is the same as the current_value, we will\n    # set the new_value to the current_value for reporting\n    else:\n        new_value = current_value\n\n    facts = dict(gconftool2={'changed': change,\n                             'key': key,\n                             'value_type': value_type,\n                             'new_value': new_value,\n                             'previous_value': current_value,\n                             'playbook_value': module.params['value']})\n\n    module.exit_json(changed=change, ansible_facts=facts)\n\n\nif __name__ == '__main__':\n    main()\n", "path": "plugins/modules/system/gconftool2.py"}], "after_files": [{"content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2016, Kenneth D. Evensen <kevensen@redhat.com>\n# Copyright (c) 2017, Abhijeet Kasurde <akasurde@redhat.com>\n# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)\n# SPDX-License-Identifier: GPL-3.0-or-later\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nDOCUMENTATION = '''\nmodule: gconftool2\nauthor:\n    - Kenneth D. Evensen (@kevensen)\nshort_description: Edit GNOME Configurations\ndescription:\n  - This module allows for the manipulation of GNOME 2 Configuration via\n    gconftool-2.  Please see the gconftool-2(1) man pages for more details.\noptions:\n  key:\n    type: str\n    description:\n    - A GConf preference key is an element in the GConf repository\n      that corresponds to an application preference. See man gconftool-2(1)\n    required: true\n  value:\n    type: str\n    description:\n    - Preference keys typically have simple values such as strings,\n      integers, or lists of strings and integers. This is ignored if the state\n      is \"get\". See man gconftool-2(1)\n  value_type:\n    type: str\n    description:\n    - The type of value being set. This is ignored if the state is \"get\".\n    choices: [ bool, float, int, string ]\n  state:\n    type: str\n    description:\n    - The action to take upon the key/value.\n    required: true\n    choices: [ absent, get, present ]\n  config_source:\n    type: str\n    description:\n    - Specify a configuration source to use rather than the default path.\n      See man gconftool-2(1)\n  direct:\n    description:\n    - Access the config database directly, bypassing server.  If direct is\n      specified then the config_source must be specified as well.\n      See man gconftool-2(1)\n    type: bool\n    default: false\n'''\n\nEXAMPLES = \"\"\"\n- name: Change the widget font to \"Serif 12\"\n  community.general.gconftool2:\n    key: \"/desktop/gnome/interface/font_name\"\n    value_type: \"string\"\n    value: \"Serif 12\"\n\"\"\"\n\nRETURN = '''\n  key:\n    description: The key specified in the module parameters\n    returned: success\n    type: str\n    sample: /desktop/gnome/interface/font_name\n  value_type:\n    description: The type of the value that was changed\n    returned: success\n    type: str\n    sample: string\n  value:\n    description: The value of the preference key after executing the module\n    returned: success\n    type: str\n    sample: \"Serif 12\"\n...\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\n\n\nclass GConf2Preference(object):\n    def __init__(self, ansible, key, value_type, value,\n                 direct=False, config_source=\"\"):\n        self.ansible = ansible\n        self.key = key\n        self.value_type = value_type\n        self.value = value\n        self.config_source = config_source\n        self.direct = direct\n\n    def value_already_set(self):\n        return False\n\n    def call(self, call_type, fail_onerr=True):\n        \"\"\" Helper function to perform gconftool-2 operations \"\"\"\n        config_source = []\n        direct = []\n        changed = False\n        out = ''\n\n        # If the configuration source is different from the default, create\n        # the argument\n        if self.config_source is not None and len(self.config_source) > 0:\n            config_source = [\"--config-source\", self.config_source]\n\n        # If direct is true, create the argument\n        if self.direct:\n            direct = [\"--direct\"]\n\n        # Execute the call\n        cmd = [\"gconftool-2\"]\n        try:\n            # If the call is \"get\", then we don't need as many parameters and\n            # we can ignore some\n            if call_type == 'get':\n                cmd.extend([\"--get\", self.key])\n            # Otherwise, we will use all relevant parameters\n            elif call_type == 'set':\n                cmd.extend(direct)\n                cmd.extend(config_source)\n                cmd.extend([\"--type\", self.value_type, \"--{0}\".format(call_type), self.key, self.value])\n            elif call_type == 'unset':\n                cmd.extend([\"--unset\", self.key])\n\n            # Start external command\n            rc, out, err = self.ansible.run_command(cmd)\n\n            if err and fail_onerr:\n                self.ansible.fail_json(msg='gconftool-2 failed with '\n                                           'error: %s' % (str(err)))\n            else:\n                changed = True\n\n        except OSError as exception:\n            self.ansible.fail_json(msg='gconftool-2 failed with exception: '\n                                       '%s' % exception)\n        return changed, out.rstrip()\n\n\ndef main():\n    # Setup the Ansible module\n    module = AnsibleModule(\n        argument_spec=dict(\n            key=dict(type='str', required=True, no_log=False),\n            value_type=dict(type='str', choices=['bool', 'float', 'int', 'string']),\n            value=dict(type='str'),\n            state=dict(type='str', required=True, choices=['absent', 'get', 'present']),\n            direct=dict(type='bool', default=False),\n            config_source=dict(type='str'),\n        ),\n        supports_check_mode=True\n    )\n\n    state_values = {\"present\": \"set\", \"absent\": \"unset\", \"get\": \"get\"}\n\n    # Assign module values to dictionary values\n    key = module.params['key']\n    value_type = module.params['value_type']\n    if module.params['value'].lower() == \"true\":\n        value = \"true\"\n    elif module.params['value'] == \"false\":\n        value = \"false\"\n    else:\n        value = module.params['value']\n\n    state = state_values[module.params['state']]\n    direct = module.params['direct']\n    config_source = module.params['config_source']\n\n    # Initialize some variables for later\n    change = False\n    new_value = ''\n\n    if state != \"get\":\n        if value is None or value == \"\":\n            module.fail_json(msg='State %s requires \"value\" to be set'\n                                 % str(state))\n        elif value_type is None or value_type == \"\":\n            module.fail_json(msg='State %s requires \"value_type\" to be set'\n                                 % str(state))\n\n        if direct and config_source is None:\n            module.fail_json(msg='If \"direct\" is \"true\" then the ' +\n                                 '\"config_source\" must be specified')\n        elif not direct and config_source is not None:\n            module.fail_json(msg='If the \"config_source\" is specified ' +\n                                 'then \"direct\" must be \"true\"')\n\n    # Create a gconf2 preference\n    gconf_pref = GConf2Preference(module, key, value_type,\n                                  value, direct, config_source)\n    # Now we get the current value, if not found don't fail\n    dummy, current_value = gconf_pref.call(\"get\", fail_onerr=False)\n\n    # Check if the current value equals the value we want to set.  If not, make\n    # a change\n    if current_value != value:\n        # If check mode, we know a change would have occurred.\n        if module.check_mode:\n            # So we will set the change to True\n            change = True\n            # And set the new_value to the value that would have been set\n            new_value = value\n        # If not check mode make the change.\n        else:\n            change, new_value = gconf_pref.call(state)\n    # If the value we want to set is the same as the current_value, we will\n    # set the new_value to the current_value for reporting\n    else:\n        new_value = current_value\n\n    facts = dict(gconftool2={'changed': change,\n                             'key': key,\n                             'value_type': value_type,\n                             'new_value': new_value,\n                             'previous_value': current_value,\n                             'playbook_value': module.params['value']})\n\n    module.exit_json(changed=change, ansible_facts=facts)\n\n\nif __name__ == '__main__':\n    main()\n", "path": "plugins/modules/system/gconftool2.py"}]}