# -*- python -*-
# ex: set syntax=python:

manifest_url = "git://github.com/CyanogenMod/android.git"
manifest_branch="froyo"

slaves = [ "slave%02d"%(i) for i in xrange(1,2) ]

repotarball="/local/android/cyanogen/cyanogen_bootstrap.tgz"

gerrit_server = "review.cyanogenmod.com"
gerrit_user = "yourid"
proprietary_url = "http://where.to.find.com/proprietaries/%(device)s.tgz"
build_branches = []
#for i in "passion inc hero heroc sholes dream_sapphire bravo bravoc espresso supersonic liberty vibrant legend vision".split(" "):
for i in "passion hero dream_sapphire".split(" "):
	build_branches.append([i,"default.xml","froyo"])

# This is the dictionary that the buildmaster pays attention to. We also use
# a shorter alias to save typing.
c = BuildmasterConfig = {}

## DB URL

# This specifies what database buildbot uses to store change and scheduler
# state
c['db_url'] = "sqlite:///state.sqlite"

## BUILDSLAVES

from buildbot.buildslave import BuildSlave
c['slaves'] = [ BuildSlave(i, i+"pw",max_builds=1) for i in slaves ]
c['slavePortnum'] = 9989

## CHANGESOURCES

from buildbot.changes.gerritchangesource import GerritChangeSource
c['change_source'] = GerritChangeSource(gerrit_server, gerrit_user)


## SCHEDULERS

## configure the Schedulers
buildernames = [ "%s_%s"%(board,manifest) for board, manifest, gerrit_branch in build_branches]

from buildbot.scheduler import Scheduler
c['schedulers'] = []
c['schedulers'].append(Scheduler(name="all", branch=None,
                                 treeStableTimer=2*60,
                                 builderNames=buildernames))
branches = {}
for board, manifest, gerrit_branch in build_branches:
	if not branches.has_key(gerrit_branch):
		branches[gerrit_branch] = []
	branches[gerrit_branch].append("%s_%s"%(board,manifest))

for branch in branches.keys():
	print branch,branches[branch]
	c['schedulers'].append(Scheduler(name=branch, branch=branch,
					 treeStableTimer=None,
					 builderNames=branches[branch]))


## BUILDERS


from buildbot.process import factory
from buildbot.steps.source import Repo
from buildbot.steps.shell import Compile
from buildbot.steps.master import  MasterShellCommand
from buildbot.steps.transfer import FileUpload
from buildbot.steps.python_twisted import Trial
from buildbot.config import BuilderConfig
from buildbot.process.properties import WithProperties

getOutputDir = WithProperties("/var/www/builds/build-%s-%s","buildername","changenumber")
getWebDir = WithProperties("http://buildmaster.mysite.com/builds/build-%s-%s","buildername","changenumber")

builders = []
for board, manifest_file, gerrit_branch in build_branches:
	f1 = factory.BuildFactory()
	f1.workdir="system"
	f1.addStep(Repo(manifest_url=manifest_url, manifest_branch=manifest_branch, manifest_file=manifest_file, tarball=repotarball))
	f1.addStep(Compile(name="clobber old output",command="rm -rf out"))

        f1.addStep(Compile( name="download proprietaries",
                            command="" + \
                                    "curl \""+proprietary_url+"\" > props.tgz;" % ({'device':board}) + \
                                    "tar zxvf props.tgz;" + \
                                    "rm props.tgz;"
                            )
                   )
	f1.addStep(Compile(name="get rommanager",command="./vendor/cyanogen/get-rommanager"))

	buildcommand = """
		     set -e
		     export LANG=C
		     . build/envsetup.sh
		     lunch cyanogen_%s-eng
		     make -j4
		     make bacon -j4
		     repo manifest -o out/target/product/%s/manifest.xml
		     """%(board,board)
	f1.addStep(Compile(name="compile everything",command=["/bin/bash","-c", buildcommand]))
        # todo should upload result of compilation somewhere else

	builddir="%s_%s"%(board,manifest_file)
	b1 = BuilderConfig(name=builddir,
			   slavenames=slaves,
			   builddir=builddir,
			   factory=f1)
	builders.append(b1)
c['builders'] = builders


## STATUS TARGETS

# 'status' is a list of Status Targets. The results of each build will be
# pushed to these targets. buildbot/status/*.py has a variety to choose from,
# including web pages, email senders, and IRC bots.

c['status'] = []

from buildbot.status import html
from buildbot.status.web import auth, authz
from buildbot.status.status_gerrit import GerritStatusPush
from buildbot.status.builder import Results

authz_cfg=authz.Authz(
    # change any of these to True to enable; see the manual for more
    # options
    gracefulShutdown = True,
    forceBuild = True,
    forceAllBuilds = True,
    pingBuilder = True,
    stopBuild = True,
    stopAllBuilds = True,
    cancelPendingBuild = True,
)
c['status'].append(html.WebStatus(http_port=8010, authz=authz_cfg))

def gerritMessageCB(buildername, build, results):
    sep="-------------------------------\n"
    message = "buildbot finished compiling your patchset\n"
    message += sep
    message += "on configuration %s\n"%(buildername)
    message += sep
    message += "the result is %s\n"%(Results[results])
    message += sep
    message += "more details %s/builders/%s/builds/%d\n"%(c['buildbotURL'],buildername,build.getNumber())
    return message,0,0
c['status'].append(GerritStatusPush(gerrit_server,gerrit_user,gerritMessageCB))

## PROJECT IDENTITY

# the 'title' string will appear at the top of this buildbot
# installation's html.WebStatus home page (linked to the 'titleURL')
# and is embedded in the title of the waterfall HTML page.

c['title'] = "froyo"
c['titleURL'] = "http://review.android.com"

# the 'buildbotURL' string should point to the location where the buildbot's
# internal web server (usually the html.WebStatus page) is visible. This
# typically uses the port number set in the Waterfall 'status' entry, but
# with an externally-visible host name which the buildbot cannot figure out
# without some help.

c['buildbotURL'] = "http://buildbot.cyanogenmod.com"
