import os
import sys
import logging

DEBUG = []
FOREGROUND = False

HOSTNAME = None
HTTP_ENDPOINTS = []


def primary_http_endpoint():
    return HTTP_ENDPOINTS[0]


HTTP_PATH_STATIC = "static"
HTTP_PATH_DOC = "doc"
HTTP_PATH_REPOSITORIES = "repositories"
HTTP_PATH_LOG = "log"
HTTP_PATH_EVENTS = "events"
HTTP_PATH_API = "mini_buildd/api"
HTTP_PATH_LOGIN = "accounts/login/"
HTTP_PATH_LOGIN_NEXT = "mini_buildd/"


#: Global directory paths
HOME_DIR = None

INCOMING_DIR = None
REPOSITORIES_DIR = None

SPOOL_DIR = None
TMP_DIR = None
LOG_DIR = None
LOG_FILE = None
ACCESS_LOG_FILE = None
CHROOTS_DIR = None
CHROOTS_LIBDIR = None

MANUAL_DIR = None

PACKAGE_TEMPLATES_DIR = "/usr/share/mini-buildd/package-templates"

#: This should never ever be changed
CHAR_ENCODING = "UTF-8"

# Compute python-version dependent install path
PY_PACKAGE_PATH = f"/usr/lib/python{sys.version_info[0]}/dist-packages"


def log_exception(log, message, exception, level=logging.ERROR):
    msg = f"{message}: {exception}"
    log.log(level, msg)
    if "exception" in DEBUG:
        log.exception(f"Exception DEBUG ({msg}):")


def python37_systemcert_workaround():
    # - python 3.7/buster just does not use the system's default cert store, although documented as such.
    # - python 3.8/bullseye seems to work just fine.
    # - This seems to be due to openssl's set_default_verify_paths() (or maybe how it's called in py 3.7).
    # - Explicitly setting env "SSL_CERT_FILE" seems to fix openssl
    # - https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=805646 (may-be the issue).
    # I guess openssl is so secure just because it does not work 99% of the time :).
    if sys.version_info < (3, 8):
        os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt"


python37_systemcert_workaround()
