#!/usr/bin/python -tt
# -*- coding: utf-8 -*-

# (c) 2013, Bruno Cornec <bcornec@mageia.org>
# based on
#     zypper
#         (c) 2013 Patrick Callahan <pmc@patrickcallahan.com>
#     previous work from Philippe Makowski <philippem@mageia.org>
#
#
# This module 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
# (at your option) any later version.
#
# This software 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 this software.  If not, see <http://www.gnu.org/licenses/>.
#
# This file is part of Ansible
#

import re
import json
import shlex
import os
import sys

DOCUMENTATION = '''
---
module: urpm
author: Bruno Cornec
short_description: Manage packages on Mageia, Mandriva and derived distributions

description:
    - Manage packages on Mageia, Mandriva and derived distributions using the urpmi and rpm tools.

version_added: "1.0"
options:
    name:
        description:
        - package name or package specifier with version C(name) or C(name-1.0).
        required: true
        aliases: [ 'pkg' ]
    state:
        description:
          - C(present) will make sure the package is installed.
            C(latest)  will make sure the latest version of the package is installed.
            C(absent)  will make sure the specified package is not installed.
        required: false
        choices: [ present, latest, absent ]
        default: "present"
    update_cache:
        description:
            - update the package database first (urpmi.update -a).
        required: false
        default: "no"
        choices: [ "yes", "no" ]

notes: []
author: Bruno Cornec
# informational: requirements for nodes
requirements: [ urpmi, rpm ]
'''

EXAMPLES = '''
- urpm: name=foo state=installed
  description: install package foo
- urpm: name=foo state=absent
  description: remove package foo
- urpm: name=foo,bar state=absent
  description: remove packages foo and bar 
- urpm: name=bar state=installed update_cache=yes
  description: update the package database (urpmi.update -a -q) and install bar (bar will be the updated if a newer version exists) 
      
'''

# Function used for getting the name of a currently installed package.
def get_current_name(m, name):
    cmd = '/usr/bin/rpm -q --qf \'%{NAME}-%{VERSION}\''
    (rc, stdout, stderr) = m.run_command("%s %s" % (cmd, name))

    if rc != 0:
        return (rc, stdout, stderr)

    syntax = "%s"

    for line in stdout.splitlines():
        if syntax % name in line:
            current_name = line.split()[0]

    return current_name

# Function used to find out if a package is currently installed.
def get_package_state(m, name):

    # rpm -q returns 0 if the package is installed,
    # 1 if it is not installed
    cmd = ['/usr/bin/rpm', '--query', '--info', name]

    rc, stdout, stderr = m.run_command(cmd, check_rc=False)

    if rc == 0:
        return True
    else:
        return False

# Function used to update the URPM database
def update_package_db(m):
    rc = m.run_command("urpmi.update -a -q")

    if rc != 0:
        m.fail_json(msg="could not update package db")
         
# Function used to make sure a package is present.
def package_present(m, name, installed_state):
    if installed_state is False:
        cmd = ['/usr/sbin/urpmi', '--no-suggest', '--auto']

        cmd.append(name)
        rc, stdout, stderr = m.run_command(cmd, check_rc=False)

        if rc == 0:
            changed=True
        else:
            changed=False
    else:
        rc = 0
        stdout = ''
        stderr = ''
        changed=False

    return (rc, stdout, stderr, changed)

# Function used to make sure a package is the latest available version.
def package_latest(m, name, installed_state):

    if installed_state is True:
        cmd = ['/usr/sbin/urpmi', '--no-suggest', '--auto', name]
        pre_upgrade_name = ''
        post_upgrade_name = ''

        # Compare the installed package before and after to know if we changed anything.
        pre_upgrade_name = get_current_name(m, name)

        rc, stdout, stderr = m.run_command(cmd, check_rc=False)

        post_upgrade_name = get_current_name(m, name)

        if pre_upgrade_name == post_upgrade_name:
            changed = False
        else:
            changed = True

        return (rc, stdout, stderr, changed)

    else:
        # If package was not installed at all just make it present.
        return package_present(m, name, installed_state)

# Function used to make sure a package is not installed.
def package_absent(m, name, installed_state):
    if installed_state is True:
        cmd = ['/usr/sbin/urpme', '--auto', name]
        rc, stdout, stderr = m.run_command(cmd)

        if rc == 0:
            changed=True
        else:
            changed=False
    else:
        rc = 0
        stdout = ''
        stderr = ''
        changed=False

    return (rc, stdout, stderr, changed)

# ===========================================
# Main control flow

URPMI_PATH = "/usr/sbin/urpmi"

def main():
    module = AnsibleModule(
        argument_spec = dict(
            name = dict(required=True, aliases=['pkg']),
            state = dict(required=False, default='present', choices=['absent', 'installed', 'latest', 'present', 'removed']),
			update_cache = dict(default="no", aliases=["update-cache"], type='bool'),
        ),
        supports_check_mode = False
    )

    if not os.path.exists(URPMI_PATH):
        module.fail_json(msg="cannot find urpmi, looking for %s" % (URPMI_PATH))

    params = module.params

    name  = params['name']
    state = params['state']
    update_cache = params['update_cache']

    rc = 0
    stdout = ''
    stderr = ''
    result = {}
    result['name'] = name
    result['state'] = state
    result['update_cache'] = update_cache

    # Decide if the name contains a version number.
    match = re.search("-[0-9]", name)
    if match:
        specific_version = True
    else:
        specific_version = False

	# Decide whether we need to update the database first
    if update_cache is True:
        update_package_db(module)

    # Get package state
    installed_state = get_package_state(module, name)

    # Perform requested action
    if state in ['installed', 'present']:
        (rc, stdout, stderr, changed) = package_present(module, name, installed_state)
    elif state in ['absent', 'removed']:
        (rc, stdout, stderr, changed) = package_absent(module, name, installed_state)
    elif state == 'latest':
        (rc, stdout, stderr, changed) = package_latest(module, name, installed_state)

    if rc != 0:
        if stderr:
            module.fail_json(msg=stderr)
        else:
            module.fail_json(msg=stdout)

    result['changed'] = changed

    module.exit_json(**result)

# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()
