# -*- coding: utf-8 -*-
'''
Interface to Red Hat tuned-adm module

:maintainer:    Syed Ali <alicsyed@gmail.com>
:maturity:      new
:depends:       tuned-adm
:platform:      Linux
'''

# Import Python libs
from __future__ import absolute_import
import re

# Import Salt libs
import salt.utils

__func_alias__ = {
    'list_': 'list',
}

__virtualname__ = 'tuned'


def __virtual__():
    '''
    Check to see if tuned-adm binary is installed on the system

    '''
    tuned_adm = salt.utils.which('tuned-adm')
    if not tuned_adm:
        return (False, 'The tuned execution module failed to load: the tuned-adm binary is not in the path.')
    return __virtualname__


def list_():
    '''
    List the profiles available

    CLI Example:

    .. code-block:: bash

        salt '*' tuned.list
    '''

    result = __salt__['cmd.run']('tuned-adm list').splitlines()
    result.pop(0)
    result.pop()
    result = [i.lstrip('- ') for i in result]
    return result


def active():
    '''
    Return current active profile

    CLI Example:

    .. code-block:: bash

        salt '*' tuned.active
    '''

    # turn off all profiles
    result = __salt__['cmd.run']('tuned-adm active')
    pattern = re.compile(r'''(?P<stmt>Current active profile:) (?P<profile>\w+.*)''')
    match = re.match(pattern, result)
    return '{0}'.format(match.group('profile'))


def off():
    '''
    Turn off all profiles

    CLI Example:

    .. code-block:: bash

        salt '*' tuned.off
    '''

    # turn off all profiles
    result = __salt__['cmd.retcode']('tuned-adm off')
    if int(result) != 0:
        return False
    return True


def profile(profile_name):
    '''
    Activate specified profile

    CLI Example:

    .. code-block:: bash

        salt '*' tuned.profile virtual-guest
    '''

    # run tuned-adm with the profile specified
    result = __salt__['cmd.retcode']('tuned-adm profile {0}'.format(profile_name))
    if int(result) != 0:
        return False
    return '{0}'.format(profile_name)

@@ -873,66 +873,257 @@
     
-result.pop(0)%0A    result.pop()%0A    result = %5Bi.l
+# Remove %22Available profiles:%22%0A    result.pop(0)%0A    # Remove %22Current active profile:.*%22%0A    result.pop()%0A    # Output can be : %22 - %3Cprofile name%3E - %3Cdescription%3E%22 (v2.7.1)%0A    # or %22 - %3Cprofile name%3E %22 (v2.4.1)%0A    result = %5Bi.split('-')%5B1%5D.
 strip(
-'- '
 ) fo

Support new version of tuned-adm binary