import os
from buildbot.buildslave import BuildSlave
from buildbot.schedulers.forcesched import ForceScheduler
from buildbot.schedulers.basic import SingleBranchScheduler
from buildbot.schedulers.timed import Nightly
from buildbot.changes import filter
from buildbot.config import BuilderConfig
from buildbot.process.factory import BuildFactory
from buildbot.process.properties import Interpolate
from buildbot.steps.shell import ShellCommand
from buildbot.status import html, words
from buildbot.status.web import authz, auth
from buildbot.status.mail import MailNotifier

PORT_WEB = 80           # Buildbot webserver port
PORT_GITHUB = 8011      # Buildbot github hook port
PORT_MASTER = 9989      # Port where buildbot master listen buildworkers
TEST_USER = 'buildbot'  # Credential to authenticate build triggers
TEST_PWD = 'docker'     # Credential to authenticate build triggers
BUILDER_NAME = 'docker'
GITHUB_DOCKER = 'github.com/dotcloud/docker'
DOCKER_PATH = '/data/docker'
BUILDER_PATH = '/data/buildbot/slave/{0}/build'.format(BUILDER_NAME)
DOCKER_BUILD_PATH = BUILDER_PATH + '/src/github.com/dotcloud/docker'

# Credentials set by setup.sh and Vagrantfile
BUILDBOT_PWD = ''
IRC_PWD = ''
IRC_CHANNEL = ''
SMTP_USER = ''
SMTP_PWD = ''
EMAIL_RCP = ''


c = BuildmasterConfig = {}

c['title'] = "Docker"
c['titleURL'] = "waterfall"
c['buildbotURL'] = "http://docker-ci.dotcloud.com/"
c['db'] = {'db_url':"sqlite:///state.sqlite"}
c['slaves'] = [BuildSlave('buildworker', BUILDBOT_PWD)]
c['slavePortnum'] = PORT_MASTER

# Schedulers
c['schedulers'] = [ForceScheduler(name='trigger', builderNames=[BUILDER_NAME,
    'coverage'])]
c['schedulers'] += [SingleBranchScheduler(name="all",
    change_filter=filter.ChangeFilter(branch='master'), treeStableTimer=None,
    builderNames=[BUILDER_NAME])]
c['schedulers'] += [Nightly(name='daily', branch=None, builderNames=['coverage'],
    hour=0, minute=30)]

# Builders
factory = BuildFactory()
factory.addStep(ShellCommand(description='Docker',logEnviron=False,usePTY=True,
    command=["sh", "-c", Interpolate("cd ..; rm -rf build; export GOPATH={0}; "
    "go get -d {1}; cd {2}; git reset --hard %(src::revision:-unknown)s; "
    "go test -v".format(BUILDER_PATH,GITHUB_DOCKER,DOCKER_BUILD_PATH))]))
c['builders'] = [BuilderConfig(name=BUILDER_NAME,slavenames=['buildworker'],
    factory=factory)]
# Docker coverage test
coverage_cmd = ('GOPATH=`pwd` go get -d github.com/dotcloud/docker\n'
    'GOPATH=`pwd` go get github.com/axw/gocov/gocov\n'
    'sudo -E GOPATH=`pwd` ./bin/gocov test github.com/dotcloud/docker | '
    './bin/gocov report')
factory = BuildFactory()
factory.addStep(ShellCommand(description='Coverage',logEnviron=False,usePTY=True,
    command=coverage_cmd))
c['builders'] += [BuilderConfig(name='coverage',slavenames=['buildworker'],
    factory=factory)]

# Status
authz_cfg = authz.Authz(auth=auth.BasicAuth([(TEST_USER, TEST_PWD)]),
    forceBuild='auth')
c['status'] = [html.WebStatus(http_port=PORT_WEB, authz=authz_cfg)]
c['status'].append(html.WebStatus(http_port=PORT_GITHUB, allowForce=True,
    change_hook_dialects={ 'github': True }))
c['status'].append(MailNotifier(fromaddr='buildbot@docker.io',
    sendToInterestedUsers=False, extraRecipients=[EMAIL_RCP],
    mode='failing', relayhost='smtp.mailgun.org', smtpPort=587, useTls=True,
    smtpUser=SMTP_USER, smtpPassword=SMTP_PWD))
c['status'].append(words.IRC("irc.freenode.net", "dockerqabot",
    channels=[IRC_CHANNEL], password=IRC_PWD, allowForce=True,
    notify_events={'exception':1, 'successToFailure':1, 'failureToSuccess':1}))
