# -*- coding: utf-8 -*-
'''
Manage Perl modules using CPAN

.. versionadded:: 2015.5.0
'''
from __future__ import absolute_import

# Import python libs
import os
import os.path
import logging

# Import salt libs
import salt.utils

log = logging.getLogger(__name__)

# Don't shadow built-ins.
__func_alias__ = {
    'list_': 'list'
}


def __virtual__():
    '''
    Only work on supported POSIX-like systems
    '''
    if salt.utils.which('cpan'):
        return True
    return (False, 'Unable to locate cpan. Make sure it is installed and in the PATH.')


def install(module):
    '''
    Install a Perl module from CPAN

    CLI Example:

    .. code-block:: bash

        salt '*' cpan.install Template::Alloy
    '''
    ret = {
        'old': None,
        'new': None,
    }

    old_info = show(module)

    cmd = 'cpan -i {0}'.format(module)
    out = __salt__['cmd.run'](cmd)

    import pprint
    pprint.pprint(out)

    if "don't know what it is" in out:
        ret['error'] = 'CPAN cannot identify this package'
        return ret

    new_info = show(module)
    ret['old'] = old_info.get('installed version', None)
    ret['new'] = new_info['installed version']

    return ret


def remove(module, details=False):
    '''
    Attempt to remove a Perl module that was installed from CPAN. Because the
    ``cpan`` command doesn't actually support "uninstall"-like functionality,
    this function will attempt to do what it can, with what it has from CPAN.

    Until this function is declared stable, USE AT YOUR OWN RISK!

    CLI Example:

    .. code-block:: bash

        salt '*' cpan.remove Old::Package
    '''
    ret = {
        'old': None,