__author__ = 'slaskawi@redhat.com'

import os
import logging
import subprocess
import re
from tempfile import NamedTemporaryFile


class BrewBuilder:

    BREW_OUTPUT_TASK = r"taskID=(\d+)"

    def __init__(self, configuration):
        self._configuration = configuration

    def build_in_brew(self):
        logging.info("Building job in Brew")
        brew_job_description = NamedTemporaryFile(delete=True)
        brew_job_description.write("[org.infinispan-infinispan]\n")
        brew_job_description.write(
            "scmurl = git://git.app.eng.bos.redhat.com/infinispan/infinispan.git#" + self._configuration.get_release_tag_name() + "\n")
        brew_job_description.write("properties = maven.test.skip.exec=true\n")
        brew_job_description.write("profiles = distribution\n")
        brew_job_description.write("\n")
        brew_job_description.write("[org.infinispan-infinispan]\n")
        brew_job_description.write("[com.jboss.datagrid-jboss-datagrid-packaging]\n")
        brew_job_description.write(
            "scmurl = git://git.app.eng.bos.redhat.com/jdg-packaging.git#" + self._configuration.get_release_tag_name() + "\n")
        brew_job_description.write("properties = maven.test.skip.exec=true\n")
        brew_job_description.write("profiles = distribution\n")
        brew_job_description.write("buildrequires = org.infinispan-infinispan\n")
        brew_job_description.flush()

        logging.info("Brew job description temporary file created in: " + brew_job_description.name)
        p = subprocess.Popen(["cat", brew_job_description.name], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
        out = p.communicate()[0]
        logging.debug("Brew job description: " + out)

        brew_command_arguments = ['brew', 'maven-chain', '--nowait', '--debug', '--force', self._configuration.get_brew_repo_for_build(),
                                  brew_job_description.name]
        if self._configuration.get_dry_run() is True:
            brew_command_arguments.insert(2, '--scratch')
        logging.info("invoking brew with commands: " + str(brew_command_arguments))

        p = subprocess.Popen(brew_command_arguments, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
        out = p.communicate()[0]
        logging.debug("Brew output: " + out)
        task_id = re.search(BrewBuilder.BREW_OUTPUT_TASK, out).group(1)
        logging.info("Invoking watch task with task id: " + task_id)
        p = subprocess.Popen(['brew', 'watch-task', task_id], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
        out = p.communicate()[0]
        logging.debug("Brew watch-task output: " + out)

        brew_job_description.close()

        self.check_brew_output(out)

    def rebuild_maven_repo(self):
        brew_command_arguments = ["brew", "regen-repo", "--nowait", self._configuration.get_brew_repo_for_regeneration()]
        p = subprocess.Popen(brew_command_arguments, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
        out = p.communicate()[0]
        logging.debug("Brew output: " + out)

        logging.info("Waiting for repo regeneration")
        subprocess.check_call(['brew', 'wait-repo', self._configuration.get_brew_repo_for_regeneration()])

    def check_brew_output(self, brew_output):
        if re.search(r"^.*[1-9] failed", brew_output, re.M) is not None:
            raise RuntimeError("Brew build failed\n" + str(brew_output))

    def upload_dependency_information(self):
        logging.info("Uploading Brew dependency information")
        command = ["scp"]
        command.extend([self._configuration.get_packaging_repo_location() + "/target/dependency-report/jdg-artifacts.txt"])
        command.extend([self._configuration.get_brew_dependency_information_destination()])
        logging.debug("Invoking scp with arguments: " + str(command))
        subprocess.check_call(command)