#!/usr/bin/env python3

import optparse
import os
import sys
import urllib3

from ruamel.yaml import YAML


API_URL = "https://api.jujucharms.com/v4/{}/meta/id-revision"

if __name__ == "__main__":
    usage = 'usage: %prog [options] bundle.yaml'
    parser = optparse.OptionParser(usage=usage)
    parser.add_option('-i', '--in-place',
                      help='Update charm revisions in place',
                      dest='in_place', action='store_true', default=False)
    (opts, args) = parser.parse_args()

    if len(args) != 1:
        print('Please provide a single bundle.yaml as the only argument')
        sys.exit(1)

    bundle = args[0]
    if not os.path.exists(bundle):
        print('Supplied bundle ({}) not found'.format(bundle))
        sys.exit(1)

    with open(bundle) as data_file:
        # use ruamel round-trip-mode YAML parsing for human readable result
        # and preservation of YAML variables
        yaml = YAML(typ='rt')
        data = yaml.load(data_file)

    http = urllib3.PoolManager()

    for k in ('applications', 'services'):
        if k in data:
            app_key = k
            break
    else:
        raise RuntimeError('unable to determine key for applications in '
                           'bundle, is this a valid bundle?')

    for app in data[app_key]:
        charm = data[app_key][app]['charm']
        # Remove any version
        charm = charm.rstrip('-0123456789')
        charm = charm.split('/')[-1]
        charm = charm.split(':')[-1]

        url = API_URL.format(charm)
        revision = http.request('GET', url)
        if revision.status == 200:
            revision = yaml.load(revision.data)['Revision']
            data[app_key][app]['charm'] = "cs:{}-{}".format(charm, revision)
    if opts.in_place:
        with open(bundle, 'w') as bundle_file:
            yaml.dump(data, bundle_file)
    else:
        yaml.dump(data, sys.stdout)
