#!/usr/bin/env python2

from __future__ import print_function
from os import environ
from pipes import quote
from pprint import pprint
from subprocess import check_call, check_output
from sys import exit, stderr
import json, urllib

cmdurl = 'https://api.travis-ci.com/repo/puppetlabs%2Fpe-puppetdb-extensions'

# https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables
repo_owner, repo_name = environ['TRAVIS_REPO_SLUG'].split('/', 2)
if repo_owner, repo_name != ('puppetlabs', 'puppetdb'):
    exit(0)

token = environ['PDB_EXT_TRAVIS_TOKEN']

def exo(cmd):
    print(' '.join(quote(arg) for arg in cmd), file=stderr)
    return check_output(cmd)

def travis_get(path):
    global cmdurl, token
    return exo(('curl', '-sS',
                '-H', 'Accept: application/json',
                '-H', 'Travis-API-Version: 3',
                '-H', 'Authorization: token ' + token,
                cmdurl + path))

def travis_post(path, body):
    global cmdurl, token
    cmd = ('curl', '-sS',
           '-H', 'Content-Type: application/json',
           '-H', 'Accept: application/json',
           '-H', 'Travis-API-Version: 3',
           '-H', 'Authorization: token ' + token,
           '-d', json.dumps(body),
           cmdurl + path)
    print(' '.join(quote(arg) for arg in cmd), file=stderr)
    check_call(cmd)

def extensions_branch_exists(branch):
    info = json.loads(travis_get('/branch/' + urllib.quote(branch)))
    if info.get('@type') == 'error':
        if info['error_type'] == 'not_found':
            return False
        pprint(info, file=stderr)
        raise Exception('unexpected error response')
    assert(info['@type'] == 'branch')
    return True


# See if travis knows about a branch with the same name in extensions,
# and if so, kick off a build of the tip.

current_branch = exo(('git', 'rev-parse', '--abbrev-ref', 'HEAD'))[:-1]
if extensions_branch_exists(current_branch):
    travis_post('/requests', {"request" : {"branch" : current_branch}})
else:
    print('No %r branch in extensions, not requesting tests' % current_branch,
          file=stderr)
