#!/usr/bin/python
# Copyright 2015 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

from __future__ import (
    absolute_import,
    print_function,
    unicode_literals,
)

str = None

__metaclass__ = type
__all__ = []

import grp
import os
import sys


def check_user():
    # At present, only root should execute this.
    if os.getuid() != 0:
        raise SystemExit("This utility may only be run as root.")


def set_group():
    # Ensure that we're running as the `maas` group.
    try:
        gr_maas = grp.getgrnam("maas")
    except KeyError:
        raise SystemExit("No such group: maas")
    else:
        os.setegid(gr_maas.gr_gid)


def set_umask():
    # Prevent creation of world-readable (or writable, executable) files.
    os.umask(0o007)


def run():
    # Force the production MAAS Django configuration.
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "maas.settings")

    # The Django configuration lives outside of sys.path.
    sys.path.append('/usr/share/maas')

    # Use Django 1.6 if the python-django16 package is installed: this is to
    # get MAAS to work on vivid: vivid ships with Django 1.7 by default and
    # MAAS isn't yet compatible with Django 1.7.
    if os.path.exists('/usr/lib/django16'):
        sys.path.insert(1, '/usr/lib/django16')

    # Let Django do the rest.
    from django.core import management
    management.execute_from_command_line()


def main():
    check_user()
    set_group()
    set_umask()
    run()


if __name__ == "__main__":
    main()
