#!/opt/deis/controller/venv/bin/python
#
# Musters data needed before `git push deis master`.
#
import json
import os
import sys
import urllib2 as urllib


# An incomplete list of domains we won't use to access the controller
IGNORE = [
    'example.com',
    '127.0.0.1',
    '127.0.1.1',
    '0.0.0.0',
    'localhost',
]


if __name__ == '__main__':
    # Set up Django so it can find deis/settings.py
    base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    sys.path.insert(0, base_path)
    os.environ['DJANGO_SETTINGS_MODULE'] = 'deis.settings'

    # Find the current Django Site object and see if the user has updated
    # it to reference a useable domain
    from django.contrib.sites.models import Site
    site = Site.objects.get_current()
    if not any(site.domain.startswith(prefix) for prefix in IGNORE):
        domain = site.domain
    # Otherwise, try our old strategy of IP lookup through external services
    else:
        try:
            # first try jsonip.com
            domain = json.loads(urllib.urlopen(
                'http://jsonip.com',
                timeout=10).read())['ip']
        except urllib.URLError:
            # fall back to an AWS internal service
            domain = urllib.urlopen(
                'http://169.254.169.254/latest/meta-data/public-ipv4',
                timeout=10).read()

    # Write a small JSON dict to stdout
    sys.stdout.write(json.dumps({'domain': domain}))
    sys.stdout.flush()
    sys.exit(0)
