'''
Publish a command from a minion to a target
'''

import zmq
import ast

import salt.crypt
import salt.payload
from salt._compat import string_types


def _get_socket():
    '''
    Return the ZeroMQ socket to use
    '''
    context = zmq.Context()
    socket = context.socket(zmq.REQ)
    socket.connect(__opts__['master_uri'])
    return socket


def _publish(
        tgt,
        fun,
        arg=None,
        expr_form='glob',
        returner='',
        timeout=5,
        form='clean'):
    '''
    Publish a command from the minion out to other minions, publications need
    to be enabled on the Salt master and the minion needs to have permission
    to publish the command. The Salt master will also prevent a recursive
    publication loop, this means that a minion cannot command another minion
    to command another minion as that would create an infinite command loop.

    The arguments sent to the minion publish function are separated with
    commas. This means that for a minion executing a command with multiple
    args it will look like this::

        salt system.example.com publish.publish '*' user.add 'foo,1020,1020'

    CLI Example::

        salt system.example.com publish.publish '*' cmd.run 'ls -la /tmp'
    '''
    serial = salt.payload.Serial(__opts__)
    if fun == 'publish.publish':
        # Need to log something here
        return {}

    if not arg:
        arg = []

    try:
        if isinstance(ast.literal_eval(arg), dict):
            arg = [arg,]
    except Exception:
        if isinstance(arg, string_types):
            arg = arg.split(',')

    auth = salt.crypt.SAuth(__opts__)
    tok = auth.gen_token('salt')
    payload = {'enc': 'aes'}
    load = {
            'cmd': 'minion_publish',
            'fun': fun,
            'arg': arg,
            'tgt': tgt,
            'tgt_type': expr_form,
            'ret': returner,
            'tok': tok,
            'tmo': timeout,
            'form': form,
            'id': __opts__['id']}
    payload['load'] = auth.crypticle.dumps(load)
    socket = _get_socket()
    socket.send(serial.dumps(payload))
    return auth.crypticle.loads(serial.loads(socket.recv()))


def publish(tgt, fun, arg=None, expr_form='glob', returner='', timeout=5):
    '''
    Publish a command from the minion out to other minions, publications need
    to be enabled on the Salt master and the minion needs to have permission
    to publish the command. The Salt master will also prevent a recursive
    publication loop, this means that a minion cannot command another minion
    to command another minion as that would create an infinite command loop.

    The arguments sent to the minion publish function are separated with
    commas. This means that for a minion executing a command with multiple
    args it will look like this::

        salt system.example.com publish.publish '*' user.add 'foo,1020,1020'

    CLI Example::

        salt system.example.com publish.publish '*' cmd.run 'ls -la /tmp'
    '''
    return _publish(tgt, fun, arg, expr_form, returner, timeout, 'clean')


def full_data(tgt, fun, arg=None, expr_form='glob', returner='', timeout=5):
    '''
    Return the full data about the publication, this is invoked in the same
    way as the publish function

    CLI Example::

        salt system.example.com publish.full_data '*' cmd.run 'ls -la /tmp'
    '''
    return _publish(tgt, fun, arg, expr_form, returner, timeout, 'full')


def runner(fun, arg=None):
    '''
    Execute a runner on the master and return the data from the runner
    function

    CLI Example::

        salt publish.runner manage.down
    '''
    serial = salt.payload.Serial(__opts__)
    if not arg:
        arg = []

    try:
        if isinstance(ast.literal_eval(arg), dict):
            arg = [arg,]
    except Exception:
        if isinstance(arg, string_types):
            arg = arg.split(',')

    auth = salt.crypt.SAuth(__opts__)
    tok = auth.gen_token('salt')
    payload = {'enc': 'aes'}
    load = {
            'cmd': 'minion_runner',
            'fun': fun,
            'arg': arg,
            'tok': tok,
            'id': __opts__['id']}
    payload['load'] = auth.crypticle.dumps(load)
    socket = _get_socket()
    socket.send(serial.dumps(payload))
    return auth.crypticle.loads(serial.loads(socket.recv()))

@@ -46,16 +46,75 @@
 et%0A'''%0A%0A
+# Import python libs%0Aimport ast%0A%0A# Import third party libs%0A
 import z
@@ -116,27 +116,35 @@
 ort zmq%0A
-i
+%0A# I
 mport 
-ast%0A
+salt libs
 %0Aimport 
@@ -216,207 +216,55 @@
 pes%0A
-%0A%0Adef _get_socket():%0A    '''%0A    Return the ZeroMQ socket to use%0A    '''%0A    context = zmq.Context()%0A    socket = context.socket(zmq.REQ)%0A    socket.connect(__opts__%5B'master_uri'%5D)%0A    return socket%0A
+from salt.exceptions import SaltReqTimeoutError
 %0A%0Ade
@@ -1504,32 +1504,80 @@
 arg.split(',')%0A%0A
+    sreq = salt.payload(__opts__%5B'master_uri'%5D)%0A
     auth = salt.
@@ -1635,37 +1635,8 @@
 t')%0A
-    payload = %7B'enc': 'aes'%7D%0A
     
@@ -1933,33 +1933,22 @@
 '%5D%7D%0A    
-payload%5B'load'%5D =
+return
  auth.cr
@@ -1959,144 +1959,73 @@
 cle.
-dumps(
 load
-)
+s(
 %0A    
-socket = _get_socket()%0A    socket.send(serial.dumps(payload))%0A    return auth.crypticle.loads(serial.loads(socket.recv()
+        sreq.send('aes', auth.crypticle.dumps(load), 1
 ))%0A%0A
@@ -3746,24 +3746,72 @@
 split(',')%0A%0A
+    sreq = salt.payload(__opts__%5B'master_uri'%5D)%0A
     auth = s
@@ -3873,37 +3873,8 @@
 t')%0A
-    payload = %7B'enc': 'aes'%7D%0A
     
@@ -4032,25 +4032,14 @@
     
-payload%5B'load'%5D =
+return
  aut
@@ -4054,143 +4054,72 @@
 cle.
-dumps(
 load
-)
+s(
 %0A    
-socket = _get_socket()%0A    socket.send(serial.dumps(payload))%0A    return auth.crypticle.loads(serial.loads(socket.recv()
+        sreq.send('aes', auth.crypticle.dumps(load), 1
 ))%0A

Use SREQ in publish module