#!/usr/bin/env python
## -*- encoding: utf-8 -*-

import ovh
import yaml
import sys
import os.path

# Instantiate. Visit https://api.ovh.com/createToken/index.cgi?GET=/me
# to get your credentials

def main(argv):

    if len(argv) == 1:
        sys.stderr.write("Error: provide a YAML compose file as first argument.\n")
        exit(1)

    if not os.path.exists(argv[1]):
        sys.stderr.write("Error: file '%s' not found.\n" % argv[0])
        sys.stderr.write("Error: provide a YAML compose file as first argument.\n")
        exit(1)

    try:
        with open(sys.argv[1], 'r') as stream:
            yml = yaml.load(stream)
    except Exception:
        sys.stderr.write("Error: provide a YAML compose file as first argument.\n")
        exit(1)

    ovh_cfg = yml["letsencrypt"]["options"]["env"]["ovh"]
    client = ovh.Client(
        endpoint=ovh_cfg["entrypoint"],
        application_key=ovh_cfg["application"]["key"],
        application_secret=ovh_cfg["application"]["secret"],
        consumer_key=ovh_cfg["consumer_key"],
    )

    # Print nice welcome message
    print "Welcome", client.get('/me')['firstname']
    domains = client.get('/domain/zone')
    print "Domains:"
    for domain in domains:
        print " - %s" % domain


if __name__ == "__main__":
    main(sys.argv)