#!/usr/bin/env python3
# -*- mode: python; -*-
#
# cloud-status - Displays status of all managed nodes
#
# Copyright 2014 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This package is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from cloudinstall.juju.state import JujuState
from subprocess import check_output

import requests
from requests.exceptions import ConnectionError
import time

MAGIC_OK_STRING = 'New user - Landscape'

def get_landscape_host():
    """ Assuming landscape has been deployed in landscape-dense-maas form,
    find the "dns-name" of the landscape web server. """
    juju = JujuState(check_output(['juju', 'status']))
    for container, (charms, units) in juju.containers.items():
        machine_no, _, lxc_id = container.split('/')
        if 'apache2' in charms:
            return juju.container(machine_no, lxc_id)['dns-name']
    raise Exception("Landscape not found!")

def main():
    host = get_landscape_host()
    while True:
        try:
            # Landscape generates a self signed cert for each install.
            r = requests.get('http://%s/' % host, verify=False)
            if MAGIC_OK_STRING in r.text:
                # now do an API call to make sure the API is up (it gives 503
                # for a while)
                r = requests.get('http://%s/api' % host, verify=False)
                if r.status_code == 200:
                    break
        except ConnectionError:
            pass
        time.sleep(10)
    print(host)

if __name__ == '__main__':
    main()
