#!/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 datetime import datetime
from tempfile import mkdtemp
from os.path import join

import click

PBSFILE = """#!/bin/bash
#PBS -l nodes=1:ppn=1
#PBS -o %s/qsub-output.txt
#PBS -e %s/qsub-error.txt
#PBS -l epilogue=/home/qiita/qiita-epilogue.sh

# Commands to run
echo $PBS_JOBID
%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])
    # 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
    lines = [' '.join(cmd)]
    datestr = datetime.now().strftime("%Y%m%d_%I%M%S.%f")
    dirpath = mkdtemp(prefix=datestr,
                      dir='/projects/qiita_data/working_dir/private-jobs/')
    fp = join(dirpath, 'private.qsub')
    with open(fp, 'w') as f:
        f.write(PBSFILE % (dirpath, dirpath, "\n".join(lines)))
    qsub_cmd = "qsub %s" % fp
    proc = Popen(qsub_cmd, shell=True, stdout=PIPE, stderr=PIPE)
    stdout, stderr = proc.communicate()
    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()
