#!/usr/bin/env python
# Copyright 2015, Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import subprocess

# import module snippets
from ansible.module_utils.basic import *


DOCUMENTATION = """
---
module: mysql_status_facts
short_description:
    - A module for gathering mysql status and global variable facts.
description:
    - A module for gathering mysql status and global variable facts.
author: Rcbops
"""

EXAMPLES = """
- name: Gather mysql status facts
  mysql_status_facts:
"""


class MysqlStatusFacts(object):
    def __init__(self, module):
        self.state_change = False
        self.module = module

    def gather_facts(self):
        """Get information about mysql status."""
        try:
            status = subprocess.check_output(["mysql", "-e", "show status"],
                                             stderr=subprocess.STDOUT)
            global_vars = subprocess.check_output(["mysql", "-e",
                                                   "show global variables"],
                                                  stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            message = 'Mysql fact collection failed: "%s".' % e.output.strip()
            self.module.fail_json(msg=message)
        else:
            lines = status.split('\n')
            lines += global_vars.split('\n')
            facts = dict(l.split('\t') for l in lines if l)
            self.module.exit_json(
                changed=self.state_change,
                ansible_facts={'mysql_status': facts})


def main():
    module = AnsibleModule(
        argument_spec=dict(
        ),
        supports_check_mode=False
    )
    mysql_facts = MysqlStatusFacts(module)
    mysql_facts.gather_facts()

if __name__ == '__main__':
    main()
