import logging
import os
import subprocess

log = logging.getLogger(__name__)


class CommandError(Exception):
    pass


def run(*args, **env_vars):
    cmd = ['openssl']
    cmd.extend(args)
    env = dict(os.environ)
    env.update(env_vars)
    log.debug('executing "%s"' % ' '.join(cmd))
    pipe = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE)
    stdout, _ = pipe.communicate()
    if pipe.returncode != 0:
        raise CommandError('openssl exited with status %d' % (
                pipe.returncode,))
    return stdout


def run_with_config(caroot, config_file, *args):
    cmd = args[0]
    args = args[1:]
    caroot = os.path.abspath(caroot)
    return run(cmd, '-config', config_file, '-batch', *args, CAROOT=caroot)
