import subprocess
import tempfile
import logging
from mariner.util import which, get_playbook_path

logger = logging.getLogger(__name__)


def make_ansible_command(hosts_file, identifier, extra_vars='{}', tags=''):
    """
    This utility will compose the command needed to run ansible, capture its
    stdout and stderr to a file
    """
    playbook = get_playbook_path()
    ansible_path = which('ansible-playbook')

    return [
        ansible_path, '-i', hosts_file,
        '--extra-vars="%s"' % extra_vars, '--tags', tags, playbook
    ]


def temp_file(identifier, std):
    return tempfile.NamedTemporaryFile(
        prefix="{identifier}_{std}".format(
            identifier=identifier, std=std), delete=False
    )


def run(arguments, **kwargs):
    """
    A small helper to run a system command using ``subprocess.Popen``. Opinionated becuase
    it will always want to
    Safely execute a ``subprocess.Popen`` call making sure that the
    executable exists and raising a helpful error message
    if it does not.

    .. note:: This should be the prefered way of calling ``subprocess.Popen``
    since it provides the caller with the safety net of making sure that
    executables *will* be found and will error nicely otherwise.

    This returns the output of the command and the return code of the
    process in a tuple: (output, returncode).
    """
    logger.info('Running command: %s' % ' '.join(arguments))
    process = subprocess.Popen(
        arguments,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        **kwargs)
    out, err = process.communicate()
    return out, err, process.returncode

@@ -832,16 +832,20 @@
 Popen%60%60.
+%0A   
  Opinion
@@ -856,20 +856,16 @@
  becuase
-%0A   
  it will
@@ -879,20 +879,16 @@
  want to
-%0A   
  Safely 
@@ -894,16 +894,20 @@
  execute
+%0A   
  a %60%60sub
@@ -947,20 +947,16 @@
 that the
-%0A   
  executa
@@ -969,16 +969,20 @@
 ists and
+%0A   
  raising
@@ -1005,20 +1005,16 @@
  message
-%0A   
  if it d
@@ -1027,225 +1027,8 @@
 t.%0A%0A
-    .. note:: This should be the prefered way of calling %60%60subprocess.Popen%60%60%0A    since it provides the caller with the safety net of making sure that%0A    executables *will* be found and will error nicely otherwise.%0A%0A
     
@@ -1092,28 +1092,24 @@
 e of the
-%0A   
  process
  in a tu
@@ -1100,16 +1100,20 @@
  process
+%0A   
  in a tu
@@ -1120,16 +1120,34 @@
 ple:
- (output
+:%0A%0A        (stdout, stderr
 , re
@@ -1155,17 +1155,16 @@
 urncode)
-.
 %0A    %22%22%22

fix docstring for process.run