import sys
from argparse import ArgumentParser

import requests

from logger import logger

BASE_URL = 'http://172.23.120.24/builds/latestbuilds/couchbase-server'

CHECKPOINT = '/home/latest'

MAX_MISSING = 3

RELEASES = {
    'spock': '5.0.0',
}


def read_latest() -> int:
    with open(CHECKPOINT) as f:
        build = f.read()
        return int(build)


def store_latest(build: int):
    logger.info('Storing build {}'.format(build))
    with open(CHECKPOINT, 'w') as f:
        f.write(str(build))


def build_exists(release: str, build: str) -> bool:
    url = '{}/{release}/{build}/'.format(BASE_URL, release=release, build=build)

    r = requests.head(url)
    return r.status_code == 200


def rpm_package_exists(release: str, build: str) -> bool:
    semver = RELEASES[release]
    package = 'couchbase-server-enterprise-{semver}-{build}-centos7.x86_64.rpm'\
        .format(semver=semver, build=build)
    url = '{}/{release}/{build}/{package}'.format(
        BASE_URL, release=release, build=build, package=package)

    r = requests.head(url)
    return r.status_code == 200


def get_args():
    parser = ArgumentParser()

    parser.add_argument('-r', '--release', dest='release',
                        default='spock')

    return parser.parse_args()


def main():
    args = get_args()

    latest = None
    build = read_latest()
    missing = 0

    while missing < MAX_MISSING:
        build += 1

        logger.info('Checking build {}'.format(build))

        if not build_exists(args.release, build):
            missing += 1
            continue

        if rpm_package_exists(args.release, build):
            latest = build

    if latest:
        store_latest(build=latest)
    else:
        sys.exit('No new build found')


if __name__ == '__main__':
    main()

@@ -1,12 +1,22 @@
+import os%0A
 import sys%0Af
@@ -177,16 +177,20 @@
 ECKPOINT
+_DIR
  = '/hom
@@ -191,22 +191,16 @@
  '/home/
-latest
 '%0A%0AMAX_M
@@ -246,16 +246,39 @@
 5.0.0',%0A
+    'vulcan': '5.1.0',%0A
 %7D%0A%0A%0Adef 
@@ -289,16 +289,28 @@
 _latest(
+release: str
 ) -%3E int
@@ -315,36 +315,91 @@
 nt:%0A    
-with open(CHECKPOINT
+checkpoint = os.path.join(CHECKPOINT_DIR, release)%0A    with open(checkpoint
 ) as f:%0A
@@ -464,24 +464,38 @@
 tore_latest(
+release: str, 
 build: int):
@@ -549,32 +549,88 @@
 d))%0A
+%0A
     
-with open(CHECKPOINT
+checkpoint = os.path.join(CHECKPOINT_DIR, release)%0A    with open(checkpoint
 , 'w
@@ -1364,32 +1364,8 @@
 se',
-%0A                       
  def
@@ -1489,16 +1489,36 @@
 _latest(
+release=args.release
 )%0A    mi
@@ -1850,16 +1850,38 @@
 _latest(
+release=args.release, 
 build=la

Support triggering of Vulcan buids