#!/usr/bin/env python3

# Copyright 2019, 2022 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Django's command-line utility for administrative tasks."""
import os
import sys
from django.core.exceptions import ImproperlyConfigured


def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'debusine.project.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    try:
        execute_from_command_line(sys.argv)
    except ImproperlyConfigured as exc:
        print("Improperly configured error:", exc, file=sys.stderr)
        sys.exit(3)
    except ValueError as exc:
        if isinstance(exc.__cause__, PermissionError):
            filename = exc.__cause__.filename or "Unknown"
            print(
                f"Permission error: {exc}. Check that the user running "
                f'debusine-admin has access to the file "{filename}".',
                file=sys.stderr,
            )
            sys.exit(3)
        else:
            raise


if __name__ == '__main__':
    main()
