# ex: set syntax=python:

import json

from buildbot.buildslave import BuildSlave
from buildbot.schedulers.forcesched import ForceScheduler
from buildbot.process.factory import BuildFactory
from buildbot.steps.source.git import Git
from buildbot.steps.shell import ShellCommand
from buildbot.config import BuilderConfig
from buildbot.status.web.authz import Authz
from buildbot.status import html
from buildbot.process.properties import WithProperties
from buildbot.steps.transfer import DirectoryUpload
from buildbot.schedulers import timed


def create_factory(config):
    factory = BuildFactory()
    factory.addStep(Git(repourl=config["repo"]))

    script = """sudo rm -rf build &&
                git clean -fdx"""

    factory.addStep(ShellCommand(command=script,
                                 description="cleaning",
                                 descriptionDone="clean"))

    script = """mkdir build &&
                sed -r 's/(Architecture = ).*/\\1%s/g' \
                    /etc/pacman.conf > pacman.conf &&
                sudo mkarchroot -C pacman.conf build/root base-devel"""

    command = WithProperties(script, "architecture")

    factory.addStep(ShellCommand(command=command,
                                 description="creating chroot",
                                 descriptionDone="chroot"))

    for package in config["packages"]:
        script = """cd %s &&
                    sudo makechrootpkg -r ../build -- -i -A &&
                    mkdir -p ../repo &&
                    find -name '*.pkg.tar.xz' | xargs -i cp {} ../repo"""

        factory.addStep(ShellCommand(command=script % package,
                                     description=["building %s" % package],
                                     descriptionDone=[package]))

    script = "repo-add repo/sugar.db.tar.gz repo/*"

    factory.addStep(ShellCommand(command=script,
                                 description="composing repo",
                                 descriptionDone="repo"))

    dest = WithProperties("~/public_html/archsugar/%s", "architecture")
    factory.addStep(DirectoryUpload(slavesrc="repo", masterdest=dest))

    return factory


def create_builder(config, slave_name, architecture):
    name = "%s-%s" % (slave_name, architecture)
    properties = {"architecture": architecture}
    factory = create_factory(config)

    return BuilderConfig(name=name,
                         slavenames=[slave_name],
                         factory=factory,
                         properties=properties)


with open("config.json") as f:
    config = json.load(f)

c = BuildmasterConfig = config["config"]

authz = Authz(forceBuild=True, forceAllBuilds=True, pingBuilder=True,
              gracefulShutdown=True, pauseSlave=True, stopBuild=True,
              stopAllBuilds=True, cancelPendingBuild=True, stopChange=True)

c["status"] = [html.WebStatus(http_port=config["webPort"], authz=authz)]

c["slaves"] = [BuildSlave(name, info["password"], max_builds=1)
               for name, info in config["slaves"].items()]

c["builders"] = []
for slave, info in config["slaves"].items():
    c["builders"].extend([create_builder(config, slave, architecture)
                          for architecture in info["architectures"]])

builderNames = [str(b.name) for b in c["builders"]]

c["schedulers"] = [ForceScheduler(name="force",
                                  builderNames=builderNames),
                   timed.Nightly(name="nightly",
                                 branch="master",
                                 builderNames=builderNames,
                                 hour=6,
                                 minute=0)]
