#!/usr/bin/env python

# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------------

from subprocess import Popen, PIPE
from os import close, remove
from tempfile import mkstemp

import click

# When Popen executes, the shell is not in interactive mode,
# so it is not sourcing any of the bash configuration files
# We need to source it so the env_script are available
SCRIPT = """#!/bin/bash

source ~/.bash_profile
%s
%s
"""


@click.command()
@click.argument('qiita_env', required=True, nargs=1)
@click.argument('command', required=True, nargs=1)
@click.argument('arguments', required=True, nargs=-1)
def start(qiita_env, command, arguments):
    """Starts the plugin environment"""
    cmd = ['qiita-private', command]
    cmd.extend(["'%s'" % arg for arg in arguments])
    fd, fp = mkstemp(suffix=".sh")
    close(fd)
    with open(fp, 'w') as f:
        f.write(SCRIPT % (qiita_env, ' '.join(cmd)))
    cmd = "bash %s" % fp
    proc = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
    stdout, stderr = proc.communicate()
    remove(fp)
    if proc.returncode and proc.returncode != 0:
        raise ValueError(
            "Error launching internal task:\n\tStdout: %s\n\tStderr: %s"
            % (stdout, stderr))


if __name__ == '__main__':
    start()
