"""
Distribution setups && support

Dist-like variable naming convention
====================================
* ``diststr``: Instance of ``str``: "buster-test-unstable"
* ``dist``: Instance of ``mini_buildd.dist.Dist``: diststr parsed && support
* ``distribution``: Instance of ``mini_buildd.model.distribution.Distribution``: Configured distribution
"""

import abc
import enum
import functools
import logging
import re

import debian.debian_support
import distro_info

from mini_buildd import call, util

LOG = logging.getLogger(__name__)


class Archs:
    """Deliver lists of Debian architectures the current system can handle"""

    _NATIVE_ARCHS_MAP = {"amd64": ["i386"]}

    @classmethod
    def _atwarn(cls, e):
        LOG.warning("Please install ``arch-test`` to get a complete list of usable archs: %s", e)

    @classmethod
    def native(cls):
        try:
            return call.Call(["arch-test", "-n"]).check().stdout.split()
        except Exception as e:
            cls._atwarn(e)
            native = call.Call(["dpkg", "--print-architecture"]).check().stdout.strip()
            return [native] + cls._NATIVE_ARCHS_MAP.get(native, [])

    @classmethod
    def available(cls):
        try:
            return call.Call(["arch-test"]).check().stdout.split()
        except Exception as e:
            cls._atwarn(e)
            return cls.native()


class DistroInfo(distro_info.DistroInfo):
    def mbd_origin(self):
        return self._distro

    def mbd_release(self, codename):
        for r in self._releases:
            if r.series == codename:
                return r
        return None

    @abc.abstractmethod
    def mbd_lts(self):
        pass


class DebianDistroInfo(DistroInfo, distro_info.DebianDistroInfo):
    def mbd_lts(self):
        """
        .. tip:: What does ``LTS`` (mini-buildd speak) include for Debian?

           For mini-buildd, ``LTS`` means ``Debian Long Term Support (LTS)`` including ``Debian Extended Long Term Support (ELTS)``.

           See: https://www.debian.org/lts/, https://wiki.debian.org/LTS/Extended
        """
        return self.lts_supported() + self.elts_supported()


class UbuntuDistroInfo(DistroInfo, distro_info.UbuntuDistroInfo):
    def mbd_lts(self):
        """
        .. tip:: What does ``LTS`` (mini-buildd speak) include for Ubuntu?

           For mini-buildd, ``LTS`` means ``Ubuntu Long Term Support (LTS)`` including ``Ubuntu Extended Security Maintenance (ESM)``.

           See: https://ubuntu.com/about/release-cycle
        """
        return self.supported_esm()  # this includes LTS


#: Available distro infos
DISTRO_INFO = {
    "Debian": DebianDistroInfo(),
    "Ubuntu": UbuntuDistroInfo(),
}

APT_KEYS = {
    "Debian": {
        "trixie": {
            "archive": "225629DF75B188BD",    # Debian Archive Automatic Signing Key (13/trixie) <ftpmaster@debian.org>
            "release": "762F67A0B2C39DE4",    # Debian Stable Release Key (13/trixie) <debian-release@lists.debian.org>
            "security": "9904613D4CCE68C6",   # Debian Security Archive Automatic Signing Key (13/trixie) <ftpmaster@debian.org>
        },
        "bookworm": {
            "archive": "B7C5D7D6350947F8",    # Debian Archive Automatic Signing Key (12/bookworm) <ftpmaster@debian.org>
            "release": "F8D2585B8783D481",    # Debian Stable Release Key (12/bookworm) <debian-release@lists.debian.org>
            "security": "254CF3B5AEC0A8F0",   # Debian Security Archive Automatic Signing Key (12/bookworm) <ftpmaster@debian.org>
        },
        "bullseye": {
            "archive": "73A4F27B8DD47936",    # Debian Archive Automatic Signing Key (11/bullseye) <ftpmaster@debian.org>
            "release": "605C66F00D6C9793",    # Debian Stable Release Key (11/bullseye) <debian-release@lists.debian.org>
            "security": "A48449044AAD5C5D",   # Debian Security Archive Automatic Signing Key (11/bullseye) <ftpmaster@debian.org>
        },
        "buster": {
            "archive": "DC30D7C23CBBABEE",    # Debian Archive Automatic Signing Key (10/buster) <ftpmaster@debian.org>
            "release": "DCC9EFBF77E11517",    # Debian Stable Release Key (10/buster) <debian-release@lists.debian.org>
            "security": "4DFAB270CAA96DFA",   # Debian Security Archive Automatic Signing Key (10/buster) <ftpmaster@debian.org>
        },
        "stretch": {
            "archive": "E0B11894F66AEC98",    # Debian Archive Automatic Signing Key (9/stretch) <ftpmaster@debian.org>  (subkey 04EE7237B7D453EC)
            "release": "EF0F382A1A7B6500",    # Debian Stable Release Key (9/stretch) <debian-release@lists.debian.org>
            "security": "EDA0D2388AE22BA9",   # Debian Security Archive Automatic Signing Key (9/stretch) <ftpmaster@debian.org>
        },
        "jessie": {
            "archive": "7638D0442B90D010",    # Debian Archive Automatic Signing Key (8/jessie) <ftpmaster@debian.org>
            "release": "CBF8D6FD518E17E1",    # Jessie Stable Release Key <debian-release@lists.debian.org>
            "security": "9D6D8F6BC857C906",   # Debian Security Archive Automatic Signing Key (8/jessie) <ftpmaster@debian.org>
        },
        "wheezy": {
            "archive": "8B48AD6246925553",    # Debian Archive Automatic Signing Key (7.0/wheezy) <ftpmaster@debian.org>
            "release": "6FB2A1C265FFB764",    # Wheezy Stable Release Key <debian-release@lists.debian.org>
        },
        "squeeze": {
            "archive": "AED4B06F473041FA",    # Debian Archive Automatic Signing Key (6.0/squeeze) <ftpmaster@debian.org>
            "release": "64481591B98321F9",    # Squeeze Stable Release Key <debian-release@lists.debian.org>
        },
        "lenny": {
            "archive": "9AA38DCD55BE302B",    # Debian Archive Automatic Signing Key (5.0/lenny) <ftpmaster@debian.org>
            "release": "4D270D06F42584E6",    # Lenny Stable Release Key <debian-release@lists.debian.org>
        },
    },
    "Ubuntu": {
        "2018": "871920D1991BC93C",   # Ubuntu Archive Automatic Signing Key (2018) <ftpmaster@ubuntu.com>
        "2012": "3B4FE6ACC0B21F32",   # Ubuntu Archive Automatic Signing Key (2012) <ftpmaster@ubuntu.com>
        "2004": "40976EAF437D05B5",   # Ubuntu Archive Automatic Signing Key <ftpmaster@ubuntu.com>
    },
    "PureOS": {
        "repository": "2B4A53F2B41CE072",   # Purism PureOS Archive (PureOS Archive Signing Key) <sysadmin@puri.sm>
    },
}

SUITE_SETUP = {
    "stable": {
        "options": {
            "uploadable": False,
        },
    },
    "hotfix": {
        "migrates_to": "stable",
    },
    "testing": {
        "migrates_to": "stable",
        "options": {
            "uploadable": False,
        },
    },
    "unstable": {
        "migrates_to": "testing",
        "options": {
            "build_keyring_package": True,
        },
    },
    "snapshot": {
        "options": {
            "experimental": True,
        },
    },
    "experimental": {
        "options": {
            "experimental": True,
            "but_automatic_upgrades": False,
        },
    },
}

SETUP = {
    "defaults": {  # Plain default values for model fields
        "distribution": {
            "sbuild_config_blocks": "set-default-path ccache",
            "sbuild_setup_blocks": "apt-setup apt-update ccache eatmydata",
            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file,bogus-mail-host,bogus-mail-host-in-debian-changelog",
            "lintian_warnfail_options": "--fail-on error,warning",
        },
    },
    "layout": {  # Layout Default
        "Default": {
            "suites": SUITE_SETUP,
            "rollback": {"stable": 6, "hotfix": 4, "testing": 3, "unstable": 9, "snapshot": 12, "experimental": 6},
        },
        "Default (no rollbacks)": {
            "suites": SUITE_SETUP,
            "rollback": {},
        },
        "Debian Developer": {
            "suites": {s: c for s, c in SUITE_SETUP.items() if s in ["stable", "testing", "unstable", "experimental"]},
            "rollback": {},
            "options": {
                "mandatory_version_regex": ".*",
                "experimental_mandatory_version_regex": ".*",
                "meta_distributions": {"unstable": "sid-unstable", "experimental": "sid-experimental"},
            },
        },
    },
    "origin": {  # Custom setup for actual distributons
        "Debian": {
            #: "Usually used" paths on a mirror. Can be used to guess individual archive URLS from a base mirror URL.
            "archive_paths": ["debian", "debian-security", "debian-ports", "debian-archive/debian", "debian-archive/debian-security", "debian-archive/debian-backports"],

            #: Canonical (internet) archives
            "archive": [
                "http://ftp.debian.org/debian/",                 # Debian (release, updates, proposed-updates and backports)
                "http://deb.debian.org/debian/",                 # alternate: CDN

                "http://security.debian.org/debian-security/",   # Debian Security (release/updates)
                "http://deb.debian.org/debian-security/",        # alternate: CDN

                "http://archive.debian.org/debian/",             # Archived Debian Releases
                "http://archive.debian.org/debian-security/",    # Archived Debian Security
                "http://archive.debian.org/debian-backports/",   # Archived Debian Backports
            ],
            "components": ["main", "contrib", "non-free", "non-free-firmware"],

            "codename": {
                "sid": {
                    "apt_keys": [APT_KEYS["Debian"]["bullseye"]["archive"], APT_KEYS["Debian"]["bookworm"]["archive"]],
                },
                "forky": {
                    "apt_keys": [APT_KEYS["Debian"]["bookworm"]["archive"], APT_KEYS["Debian"]["trixie"]["archive"]],
                    "extra_sources": [
                        {
                            "codename": "forky-security",
                            "apt_keys": [APT_KEYS["Debian"]["bookworm"]["security"], APT_KEYS["Debian"]["trixie"]["security"]],
                            "priority": 500,
                            "options": {
                                "remove_from_component": "updates/",
                            },
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "forky-backports",
                            "apt_keys": [APT_KEYS["Debian"]["bookworm"]["archive"], APT_KEYS["Debian"]["trixie"]["archive"]],
                        },
                    ],
                },
                "trixie": {
                    "apt_keys": [APT_KEYS["Debian"]["bookworm"]["archive"], APT_KEYS["Debian"]["trixie"]["archive"], APT_KEYS["Debian"]["trixie"]["release"]],
                    "extra_sources": [
                        {
                            "codename": "trixie-security",
                            "apt_keys": [APT_KEYS["Debian"]["bookworm"]["security"], APT_KEYS["Debian"]["trixie"]["security"]],
                            "priority": 500,
                            "options": {
                                "remove_from_component": "updates/",
                            },
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "trixie-backports",
                            "apt_keys": [APT_KEYS["Debian"]["bookworm"]["archive"], APT_KEYS["Debian"]["trixie"]["archive"]],
                        },
                    ],
                },
                "bookworm": {
                    "lintian_version": "2.116.3",
                    "apt_keys": [APT_KEYS["Debian"]["buster"]["archive"], APT_KEYS["Debian"]["bullseye"]["archive"], APT_KEYS["Debian"]["bookworm"]["release"]],
                    "extra_sources": [
                        {
                            "codename": "bookworm-security",
                            "apt_keys": [APT_KEYS["Debian"]["bullseye"]["security"], APT_KEYS["Debian"]["bookworm"]["security"]],
                            "priority": 500,
                            "options": {
                                "remove_from_component": "updates/",
                            },
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "bookworm-backports",
                            "apt_keys": [APT_KEYS["Debian"]["bullseye"]["archive"], APT_KEYS["Debian"]["bookworm"]["archive"]],
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "bookworm-backports-sloppy",
                            "apt_keys": [APT_KEYS["Debian"]["bullseye"]["archive"], APT_KEYS["Debian"]["bookworm"]["archive"]],
                        },
                    ],
                },
                "bullseye": {
                    "lintian_version": "2.104.0",
                    "components": ["main", "contrib", "non-free"],
                    "apt_keys": [APT_KEYS["Debian"]["buster"]["archive"], APT_KEYS["Debian"]["bullseye"]["archive"], APT_KEYS["Debian"]["bullseye"]["release"]],
                    "extra_sources": [
                        {
                            "codename": "bullseye-security",
                            "apt_keys": [APT_KEYS["Debian"]["buster"]["security"], APT_KEYS["Debian"]["bullseye"]["security"]],
                            "priority": 500,
                            "options": {
                                "remove_from_component": "updates/",
                            },
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "bullseye-backports",
                            "apt_keys": [APT_KEYS["Debian"]["buster"]["archive"], APT_KEYS["Debian"]["bullseye"]["archive"], APT_KEYS["Debian"]["bookworm"]["archive"]],
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "bullseye-backports-sloppy",
                            "apt_keys": [APT_KEYS["Debian"]["buster"]["archive"], APT_KEYS["Debian"]["bullseye"]["archive"], APT_KEYS["Debian"]["bookworm"]["archive"]],
                        },
                    ],
                },
                "buster": {
                    "lintian_version": "2.15.0",
                    "components": ["main", "contrib", "non-free"],
                    "apt_keys": [APT_KEYS["Debian"]["buster"]["archive"], APT_KEYS["Debian"]["buster"]["release"], APT_KEYS["Debian"]["bullseye"]["archive"]],
                    "extra_sources": [
                        {
                            "codename": "buster/updates",
                            "apt_keys": [APT_KEYS["Debian"]["buster"]["security"], APT_KEYS["Debian"]["bullseye"]["security"]],
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "buster",
                                    "Label": "Debian-Security",
                                },
                                "remove_from_component": "updates/",
                            },
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "buster-backports",
                            "apt_keys": [APT_KEYS["Debian"]["buster"]["archive"], APT_KEYS["Debian"]["bullseye"]["archive"], APT_KEYS["Debian"]["bookworm"]["archive"]],
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "buster-backports-sloppy",
                            "apt_keys": [APT_KEYS["Debian"]["buster"]["archive"], APT_KEYS["Debian"]["bullseye"]["archive"], APT_KEYS["Debian"]["bookworm"]["archive"]],
                        },
                    ],
                    "distribution": {
                        "options": {
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                            "lintian_warnfail_options": "--fail-on-warnings",
                        },
                    },
                },
                "stretch": {
                    "lintian_version": "2.5.50.4",
                    "components": ["main", "contrib", "non-free"],
                    "apt_keys": [APT_KEYS["Debian"]["stretch"]["archive"], APT_KEYS["Debian"]["buster"]["archive"], APT_KEYS["Debian"]["bullseye"]["archive"], APT_KEYS["Debian"]["stretch"]["release"]],
                    "extra_sources": [
                        {
                            "codename": "stretch/updates",
                            "apt_keys": [APT_KEYS["Debian"]["stretch"]["security"], APT_KEYS["Debian"]["buster"]["security"]],
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "stretch",
                                    "Label": "Debian-Security",
                                },
                                "remove_from_component": "updates/",
                            },
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "stretch-backports",
                            "apt_keys": [APT_KEYS["Debian"]["buster"]["archive"], APT_KEYS["Debian"]["bullseye"]["archive"]],
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "stretch-backports-sloppy",
                            "apt_keys": [APT_KEYS["Debian"]["buster"]["archive"], APT_KEYS["Debian"]["bullseye"]["archive"]],
                        },
                    ],
                    "distribution": {
                        "options": {
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                            "lintian_warnfail_options": "--fail-on-warnings",
                        },
                    },
                },
                "jessie": {
                    "lintian_version": "2.5.30+deb8u4",
                    "components": ["main", "contrib", "non-free"],
                    "apt_keys": [APT_KEYS["Debian"]["wheezy"]["archive"], APT_KEYS["Debian"]["jessie"]["release"], APT_KEYS["Debian"]["jessie"]["archive"]],
                    "extra_sources": [
                        {
                            "codename": "jessie/updates",
                            "apt_keys": [APT_KEYS["Debian"]["jessie"]["security"], APT_KEYS["Debian"]["stretch"]["security"]],
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "jessie",
                                    "Label": "Debian-Security",
                                },
                                "remove_from_component": "updates/",
                            },
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "jessie-backports",
                            "apt_keys": [APT_KEYS["Debian"]["wheezy"]["archive"], APT_KEYS["Debian"]["jessie"]["archive"]],
                            "options": {
                                "check_valid_until": False,
                            },
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "jessie-backports-sloppy",
                            "apt_keys": [APT_KEYS["Debian"]["wheezy"]["archive"], APT_KEYS["Debian"]["jessie"]["archive"]],
                            "options": {
                                "check_valid_until": False,
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            # jessie sources 'archive.debian.org' and 'ftp.debian.org' are not the same:
                            # * jessie from archive.debian.org needs this setting (as the Release file is signed with an expired key, and jessie's apt just won't work).
                            # * jessie from ftp.debian.org (was left there for LTS for 'amd64 armel armhf i386' only) would work w/o that flag, as it is signed differently.
                            # However, both archives will match the jessie source, and both could potentially be used.
                            "sbuild_setup_blocks": "apt-allow-unauthenticated apt-setup apt-key-binary apt-update ccache eatmydata",
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                            "lintian_warnfail_options": "--fail-on-warnings",
                        },
                    },
                },
                "wheezy": {
                    "lintian_version": "2.5.10.4",
                    "components": ["main", "contrib", "non-free"],
                    "apt_keys": [APT_KEYS["Debian"]["wheezy"]["archive"], APT_KEYS["Debian"]["wheezy"]["release"], APT_KEYS["Debian"]["jessie"]["archive"]],
                    "extra_sources": [
                        {
                            "codename": "wheezy/updates",
                            "apt_keys": [APT_KEYS["Debian"]["wheezy"]["archive"], APT_KEYS["Debian"]["jessie"]["security"]],
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "wheezy",
                                    "Label": "Debian-Security",
                                },
                                "remove_from_component": "updates/",
                                "check_valid_until": False,
                            },
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "wheezy-backports",
                            "apt_keys": [APT_KEYS["Debian"]["wheezy"]["archive"], APT_KEYS["Debian"]["jessie"]["archive"]],
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "wheezy-backports-sloppy",
                            "apt_keys": [APT_KEYS["Debian"]["wheezy"]["archive"], APT_KEYS["Debian"]["jessie"]["archive"]],
                        },
                    ],
                    "distribution": {
                        "options": {
                            "sbuild_setup_blocks": "apt-allow-unauthenticated apt-setup apt-key-binary apt-update ccache eatmydata",
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                            "lintian_warnfail_options": "--fail-on-warnings",
                        },
                    },
                    "chroot": {
                        "options": {
                            "debootstrap_extra_options": "--include=realpath",
                        },
                    },
                },
                "squeeze": {
                    "broken": "Only works with sbuild < 0.84",

                    "lintian_version": "2.4.3+squeeze1",
                    "components": ["main", "contrib", "non-free"],
                    "apt_keys": [APT_KEYS["Debian"]["squeeze"]["archive"], APT_KEYS["Debian"]["squeeze"]["release"]],
                    "extra_sources": [
                        {
                            "codename": "squeeze/updates",
                            "apt_keys": [APT_KEYS["Debian"]["squeeze"]["archive"], APT_KEYS["Debian"]["jessie"]["security"]],
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "squeeze",
                                    "Label": "Debian-Security",
                                },
                                "remove_from_component": "updates/",
                                "check_valid_until": False,
                            },
                        },
                        {
                            "codename": "squeeze-lts",
                            "apt_keys": [APT_KEYS["Debian"]["wheezy"]["archive"]],
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "squeeze-backports",
                            "apt_keys": [APT_KEYS["Debian"]["squeeze"]["archive"], APT_KEYS["Debian"]["wheezy"]["archive"]],
                        },
                    ],
                    "distribution": {
                        "options": {
                            "build_dep_resolver": 0,  # util.models().Distribution.RESOLVER_APT
                            "sbuild_setup_blocks": "apt-no-check-valid-until apt-allow-unauthenticated apt-setup apt-key-add apt-update ccache eatmydata",
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                            "lintian_warnfail_options": "--fail-on-warnings",
                        },
                    },
                    "chroot": {
                        "options": {
                            "debootstrap_extra_options": "--include=realpath",
                        },
                    },
                },
                "lenny": {
                    "broken": "Cannot build test packages (only dh7 available)",

                    "lintian_version": "1.24.2.1+lenny1",
                    "components": ["main", "contrib", "non-free"],
                    "apt_keys": [APT_KEYS["Debian"]["squeeze"]["archive"], APT_KEYS["Debian"]["lenny"]["release"]],
                    "extra_sources": [
                        {
                            "codename": "lenny/updates",
                            "apt_keys": [APT_KEYS["Debian"]["lenny"]["archive"], APT_KEYS["Debian"]["jessie"]["security"]],
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "lenny",
                                    "Label": "Debian-Security",
                                },
                                "remove_from_component": "updates/",
                                "check_valid_until": False,
                            },
                        },
                        {
                            "origin": "Debian Backports",
                            "codename": "lenny-backports",
                            "apt_keys": [APT_KEYS["Debian"]["squeeze"]["archive"]],
                        },
                    ],
                    "distribution": {
                        "options": {
                            "sbuild_setup_blocks": "apt-no-check-valid-until apt-allow-unauthenticated apt-setup apt-key-add apt-update ccache eatmydata",
                            "lintian_extra_options": "--info",
                            "lintian_warnfail_options": "--fail-on-warnings",
                        },
                    },
                    "chroot": {
                        "options": {
                            "debootstrap_command": "/usr/sbin/mini-buildd-debootstrap-uname-2.6",
                            "debootstrap_extra_options": "--include=realpath,timeout",
                        },
                    },
                },
            },
        },
        #: Ubuntu (https://wiki.ubuntu.com/Releases)
        #:
        #: Keep all active LTS and the four most recent releases.
        "Ubuntu": {
            "archive_paths": ["ubuntu", "ubuntu-old"],
            "archive": [
                "http://archive.ubuntu.com/ubuntu/",       # Releases
                "http://security.ubuntu.com/ubuntu/",      # Security
                "http://old-releases.ubuntu.com/ubuntu/",  # Older Releases
            ],
            "components": ["main", "universe", "restricted", "multiverse"],

            "codename": {
                "plucky": {  # plucky: 25.04
                    "lintian_version": "2.121.2ubuntu1",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "plucky-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "plucky",
                                    "Suite": "plucky-security",
                                },
                            },
                        },
                        {
                            "codename": "plucky-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "plucky",
                                    "Suite": "plucky-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                        },
                        "arch_optional": ["i386"],
                    },
                },
                "oracular": {  # oracular: 24.10
                    "lintian_version": "2.118.0ubuntu1",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "oracular-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "oracular",
                                    "Suite": "oracular-security",
                                },
                            },
                        },
                        {
                            "codename": "oracular-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "oracular",
                                    "Suite": "oracular-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                        },
                        "arch_optional": ["i386"],
                    },
                },
                "noble": {  # noble: 24.04 LTS 2029
                    "lintian_version": "2.117.0ubuntu1",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "noble-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "noble",
                                    "Suite": "noble-security",
                                },
                            },
                        },
                        {
                            "codename": "noble-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "noble",
                                    "Suite": "noble-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                        },
                        "arch_optional": ["i386"],
                    },
                },
                "mantic": {  # mantic: 23.10
                    "lintian_version": "2.116.3ubuntu3",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "mantic-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "mantic",
                                    "Suite": "mantic-security",
                                },
                            },
                        },
                        {
                            "codename": "mantic-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "mantic",
                                    "Suite": "mantic-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                        },
                        "arch_optional": ["i386"],
                    },
                },
                "lunar": {  # lunar: 23.04
                    "lintian_version": "2.116.3ubuntu1",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "lunar-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "lunar",
                                    "Suite": "lunar-security",
                                },
                            },
                        },
                        {
                            "codename": "lunar-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "lunar",
                                    "Suite": "lunar-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                        },
                        "arch_optional": ["i386"],
                    },
                },
                "kinetic": {  # kinetic: 22.10
                    "lintian_version": "2.115.3ubuntu2",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "kinetic-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "kinetic",
                                    "Suite": "kinetic-security",
                                },
                            },
                        },
                        {
                            "codename": "kinetic-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "kinetic",
                                    "Suite": "kinetic-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                        },
                        "arch_optional": ["i386"],
                    },
                },
                "jammy": {  # jammy: 22.04 LTS 2027
                    "lintian_version": "2.114.0ubuntu1",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "jammy-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "jammy",
                                    "Suite": "jammy-security",
                                },
                            },
                        },
                        {
                            "codename": "jammy-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "jammy",
                                    "Suite": "jammy-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                        },
                        "arch_optional": ["i386"],
                    },
                },
                "impish": {  # impish: 21.10
                    "lintian_version": "2.104.0ubuntu3",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "impish-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "impish",
                                    "Suite": "impish-security",
                                },
                            },
                        },
                        {
                            "codename": "impish-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "impish",
                                    "Suite": "impish-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                        },
                        "arch_optional": ["i386"],
                    },
                },
                "hirsute": {  # hirsute: 21.04
                    "lintian_version": "2.104.0ubuntu1",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "hirsute-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "hirsute",
                                    "Suite": "hirsute-security",
                                },
                            },
                        },
                        {
                            "codename": "hirsute-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "hirsute",
                                    "Suite": "hirsute-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                        },
                        "arch_optional": ["i386"],
                    },
                },
                "groovy": {  # groovy: 20.10
                    "lintian_version": "2.89.0",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "groovy-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "groovy",
                                    "Suite": "groovy-security",
                                },
                            },
                        },
                        {
                            "codename": "groovy-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "groovy",
                                    "Suite": "groovy-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                        },
                        "arch_optional": ["i386"],
                    },
                },
                "focal": {  # focal: 20.04 LTS 2025 ESM 2030
                    "lintian_version": "2.62.0",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2012"], APT_KEYS["Ubuntu"]["2018"]],
                    "extra_sources": [
                        {
                            "codename": "focal-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "focal",
                                    "Suite": "focal-security",
                                },
                            },
                        },
                        {
                            "codename": "focal-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "focal",
                                    "Suite": "focal-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "deb_build_options": "noddebs",
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                        },
                        # Ubuntu drops i386 (starting with focal)
                        # 'focal' still has i386 repo (debootrap still works), so i386 is still picked
                        # by mini-buildd's setup. However, builds no longer work (default resolver
                        # aptitude missing).
                        # Choosing "apt" resolver would master this hurdle, but this would also change
                        # the default resolver for amd64. Imho best solution for mini-buildd's setup
                        # is to make this arch optional.
                        # Ref: https://discourse.ubuntu.com/t/community-process-for-32-bit-compatibility/12598?u=d0od
                        "arch_optional": ["i386"],
                        "lintian_warnfail_options": "",
                    },
                },
                "bionic": {  # bionic: 18.04 LTS 2023 ESM 2028
                    "lintian_version": "2.5.81ubuntu1",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2012"]],
                    "extra_sources": [
                        {
                            "codename": "bionic-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "bionic",
                                    "Suite": "bionic-security",
                                },
                            },
                        },
                        {
                            "codename": "bionic-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "bionic",
                                    "Suite": "bionic-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            # Starting with cosmic (18.10), Ubuntu uses 'ddeb' as file appendix for automated debug packages.
                            # reprepro can't handle these yet -- so this is needed for a workaround.
                            "deb_build_options": "noddebs",
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                            "lintian_warnfail_options": "--fail-on-warnings",
                        },
                    },
                },
                "xenial": {  # xenial: 16.04 LTS 2021 ESM 2026
                    "lintian_version": "2.5.43",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2004"], APT_KEYS["Ubuntu"]["2012"]],
                    "extra_sources": [
                        {
                            "codename": "xenial-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "xenial",
                                    "Suite": "xenial-security",
                                },
                            },
                        },
                        {
                            "codename": "xenial-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "xenial",
                                    "Suite": "xenial-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "sbuild_setup_blocks": "apt-setup apt-key-add apt-update ccache eatmydata",
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                            "lintian_warnfail_options": "--fail-on-warnings",
                        },
                    },
                },
                "trusty": {  # trusty: 14.04 LTS 2019 ESM 2024
                    "broken": "``upstart`` install fails in build chroots",

                    "lintian_version": "2.5.22ubuntu1",
                    "apt_keys": [APT_KEYS["Ubuntu"]["2004"], APT_KEYS["Ubuntu"]["2012"]],
                    "extra_sources": [
                        {
                            "codename": "trusty-security",
                            "priority": 500,
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "trusty",
                                    "Suite": "trusty-security",
                                },
                            },
                        },
                        {
                            "codename": "trusty-backports",
                            "options": {
                                "extra_identifiers": {
                                    "Codename": "trusty",
                                    "Suite": "trusty-backports",
                                },
                            },
                        },
                    ],
                    "distribution": {
                        "options": {
                            "sbuild_setup_blocks": "apt-setup apt-key-add apt-update ccache eatmydata",
                            "lintian_extra_options": "--info --suppress-tags bad-distribution-in-changes-file",
                            "lintian_warnfail_options": "--fail-on-warnings",
                        },
                    },
                    "chroot": {
                        "options": {
                            "debootstrap_extra_options": "--include=realpath",
                        },
                    },
                },
            },
        },

        #: PureOS (https://pureos.net/)
        "PureOS": {
            "archive_paths": [],
            "archive": [
                "https://mirror.fsf.org/pureos/",
            ],
            "components": ["main"],

            "codename": {
                "amber": {
                    "apt_keys": [APT_KEYS["PureOS"]["repository"]],
                    "extra_sources": [
                        {
                            "codename": "amber-security",
                            "priority": 500,
                        },
                        {
                            "codename": "amber-updates",
                        }
                    ],
                },
            },
        },
    },
}


def setup_origins():
    return SETUP["origin"].keys()


def setup_codenames():
    codenames = []
    for o in setup_origins():
        codenames.extend(SETUP["origin"][o]["codename"])
    return codenames


VENDOR_CODENAMES_FUNC = {
    "": lambda origin: [codename for codename in DISTRO_INFO[origin].supported() if codename in setup_codenames()],
    "lts": lambda origin: [codename for codename in DISTRO_INFO[origin].supported() + DISTRO_INFO[origin].mbd_lts() if codename in setup_codenames()],
    "all": lambda origin: [codename for codename, setup in SETUP["origin"][origin]["codename"].items() if setup.get("broken") is None],
}


def setup_codenames_from_origin(origin, modifier=""):
    try:
        return VENDOR_CODENAMES_FUNC[modifier](origin)
    except KeyError as e:
        raise util.HTTPBadRequest(f"Unknown codenames selector: '{origin}:{modifier}' (use '{'|'.join(setup_origins())}[:{'|'.join(VENDOR_CODENAMES_FUNC.keys())}]'") from e


def _idi_codenames():
    for di in DISTRO_INFO.values():
        yield from di.all


def di_codenames():
    return list(_idi_codenames())


def guess_origin(codename):
    """
    Guess Origin from codename

    >>> guess_origin("rex")  # only via distro info
    'Debian'
    >>> guess_origin("warty")  # only via distro info
    'Ubuntu'
    >>> guess_origin("bullseye")  # via setup
    'Debian'
    """
    for origin, setup in SETUP["origin"].items():
        if codename in setup["codename"]:
            return origin

        # Check if we can find codename in distro info
        di = DISTRO_INFO.get(origin)
        if di and codename in di.all:
            return origin
    return None


def is_base_source(origin, codename):
    """Heuristics (for setup) whether this is a base source"""
    return origin in SETUP["origin"] and re.match(r"^[a-z]+$", codename) and codename != "experimental"


#: List of Debian codenames using something ``3.1`` as main version (all <= squeeze)
DEBIAN_MAJOR_MINOR_CODENAMES = ["buzz", "rex", "bo", "hamm", "slink", "potato", "woody", "sarge", "etch", "lenny", "squeeze"]


def guess_codeversion(origin, codename, version):
    """
    Get recommended codeversion from origin/codename/version triple

    ``codename`` is essentially one number representing the release version, which can later be used as in
    mandatory version part, or for sorting codenames.

    ``version`` may be from a ``Release`` file (like '11.3' for bullseye), or from ``distro-info-data``
    (just '11'). If empty, ``~CODENAME`` is returned.

    Some heuristics (tailored for Debian and Ubuntu, but may work fine for other origins) are applied to
    produce a reasonable ``codeversion``.

    In Debian,
      - point release <= sarge had the 'M.PrN' syntax (with 3.1 being a major release).
      - point release in squeeze used 'M.0.N' syntax.
      - point releases for >= wheezy have the 'M.N' syntax (with 7.1 being a point release).
      - testing and unstable do not gave a version in Release and fall back to uppercase codename

    Ubuntu just uses YY.MM which we can use as-is.

    >>> guess_codeversion("Debian", "sarge", "3.1r8")
    '31'
    >>> guess_codeversion("Debian", "etch", "4.0r9")
    '40'
    >>> guess_codeversion("Debian", "squeeze", "6.0.6")
    '60'
    >>> guess_codeversion("Debian", "wheezy", "7.0")
    '7'
    >>> guess_codeversion("Debian", "wheezy", "7.1")
    '7'
    >>> guess_codeversion("Ubuntu", "quantal", "12.10")
    '1210'
    """
    if not version:
        return "~" + codename.upper()

    ver_split = version.split(".")

    def number(no):
        """Be sure to not fail (return empty str instead), and only use *starting* digits"""
        v = ver_split[no] if len(ver_split) > no else ""
        m = re.search(r"^(\d+)", v)
        return m.group(1) if m else ""

    if origin == "Debian" and codename not in DEBIAN_MAJOR_MINOR_CODENAMES:
        return number(0)  # Debian >= wheezy
    return f"{number(0)}{number(1)}"


@functools.total_ordering
class Codename():
    def __init__(self, codename, origin="", version=""):
        self.codename = codename
        self.origin = origin if origin else guess_origin(codename)

        di = DISTRO_INFO.get(self.origin)

        # Set or compute version (may be empty string)
        if not version and di is not None:
            r = di.mbd_release(codename)
            version = di.version(self.codename) if (r is not None and r.release is not None) else ""  # Version might be non-empty in distro-info-data even if not released

        # Guess codeversion
        self.codeversion = guess_codeversion(self.origin, self.codename, version)

        # Compute cmpversion
        try:
            if di is None:
                raise util.HTTPUnavailable("No distro info")

            version = di.version(codename)
            if not version:
                raise util.HTTPUnavailable("No version in distro info")

            self.cmpversion = debian.debian_support.Version(version.replace(" ", "+"))  # Some Ubuntu versions need " LTS"->"+LTS" to produce valid version strings
        except Exception:
            self.cmpversion = debian.debian_support.Version("9999")

        self.setup = SETUP["origin"].get(self.origin, {}).get("codename", {}).get(self.codename)
        self.has_setup = self.setup is not None
        if not self.has_setup:
            self.setup = self._default_setup()

    def _default_setup(self):
        if self.origin == "Debian":
            return {
                "extra_sources": [
                    {
                        "codename": f"{self.codename}-security",
                        "priority": 500,
                        "options": {
                            "remove_from_component": "updates/",
                        },
                    },
                    {
                        "origin": "Debian Backports",
                        "codename": f"{self.codename}-backports",
                    },
                ]
            }
        if self.origin == "Ubuntu":
            return {
                "apt_keys": [APT_KEYS["Ubuntu"]["2018"]],
                "extra_sources": [
                    {
                        "codename": f"{self.codename}-security",
                        "priority": 500,
                        "options": {
                            "extra_identifiers": {"Codename": self.codename, "Suite": f"{self.codename}-security"},
                        },
                    },
                    {
                        "codename": f"{self.codename}-backports",
                        "options": {
                            "extra_identifiers": {"Codename": self.codename, "Suite": f"{self.codename}-backports"},
                        },
                    },
                ],
                "distribution": {
                    "options": {
                        "deb_build_options": "noddebs",
                    },
                    "arch_optional": ["i386"],
                }
            }
        return {}

    def setup_extra_sources(self):
        return self.setup.get("extra_sources", [])

    def setup_distribution_options(self):
        return util.mdget(self.setup, ["distribution", "options"], {})

    def setup_chroot_options(self):
        return util.mdget(self.setup, ["chroot", "options"], {})

    def setup_arch_optional(self):
        return util.mdget(self.setup, ["distribution", "arch_optional"], [])

    def setup_components(self):
        return util.mdget(self.setup, ["components"], util.mdget(SETUP, ["origin", self.origin, "components"], ["main"]))

    def __str__(self):
        return f"{self.origin} '{self.codename}' ({self.codeversion})"

    def __hash__(self):
        return hash(self.codename)

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.origin == other.origin and self.codename == other.codename
        return NotImplemented

    def __lt__(self, other):
        if isinstance(other, self.__class__):
            if self.origin == other.origin:
                return self.cmpversion < other.cmpversion
            return self.origin and other.origin and self.origin < other.origin
        return NotImplemented


class SbuildCheck():
    """
    Generic support for sbuild checks (lintian, piuparts, autopkgtest)

    >>> SbuildCheck("lindian", "disabled")  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    util.HTTPBadRequest: Unknown sbuild checker: lindian (valid options: lintian,piuparts,autopkgtest) (HTTP 400 Bad request syntax or unsupported method)

    >>> SbuildCheck("lintian", "warnfall")  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    util.HTTPBadRequest: Unknown sbuild check mode: warnfall (valid options: DISABLED,IGNORE,ERRFAIL,WARNFAIL) (HTTP 400 Bad request syntax or unsupported method)

    >>> sc = SbuildCheck("lintian", "warnfail")
    >>> sc.checker
    'lintian'
    >>> sc.mode
    <Mode.WARNFAIL: 3>
    """

    class Mode(enum.Enum):
        DISABLED = 0
        IGNORE = 1
        ERRFAIL = 2
        WARNFAIL = 3

        def __str__(self):
            return {
                self.DISABLED: "Don't run check",
                self.IGNORE: "Run check but ignore results",
                self.ERRFAIL: "Run check and fail on errors",
                self.WARNFAIL: "Run check and fail on warnings",
            }[self]

    CHECKERS = ["lintian", "piuparts", "autopkgtest"]
    CHOICES = [(mode.value, mode.name) for mode in Mode]

    #: From sbuild source code: We may expect these textual statuses:
    STATUSES_PASS = ["pass", "info"]
    STATUSES_WARN = ["warn", "no tests"]
    STATUSES_FAIL = ["error", "fail"]

    def __init__(self, checker, mode):
        if checker not in self.CHECKERS:
            raise util.HTTPBadRequest(f"Unknown sbuild checker: {checker} (valid options: {','.join(self.CHECKERS)})")
        self.checker = checker
        try:
            self.mode = self.Mode[mode.upper() if isinstance(mode, str) else mode]
        except KeyError as e:
            raise util.HTTPBadRequest(f"Unknown sbuild check mode: {mode} (valid options: {','.join([mode.name for mode in self.Mode])})") from e

    @classmethod
    def desc(cls):
        return "Mode to control if a check should prevent package installation (for non-experimental suites)."

    @classmethod
    def usage(cls):
        return ", ".join([f"'{mode.name}' ({mode})" for mode in cls.Mode])

    def check(self, status, ignore=False):
        """Check if status is ok in this mode"""
        return \
            ignore or \
            status in self.STATUSES_PASS or \
            self.mode in [self.Mode.DISABLED, self.Mode.IGNORE] or \
            (status in self.STATUSES_WARN and self.mode is not self.Mode.WARNFAIL)


class Dist():
    """
    A mini-buildd distribution string

    Normal distribution:

    >>> d = Dist("squeeze-test-stable")
    >>> d.codename, d.repository, d.suite
    ('squeeze', 'test', 'stable')
    >>> d.get()
    'squeeze-test-stable'

    Rollback distribution:

    >>> d = Dist("squeeze-test-stable-rollback5")
    >>> d.is_rollback
    True
    >>> d.get(rollback=False)
    'squeeze-test-stable'
    >>> d.codename, d.repository, d.suite, d.rollback
    ('squeeze', 'test', 'stable', 'rollback5')
    >>> d.get()
    'squeeze-test-stable-rollback5'
    >>> d.rollback_no
    5

    Malformed distributions:

    >>> Dist("-squeeze-stable")  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    util.HTTPBadRequest: Malformed distribution '-squeeze-stable': Must be '<codename>-<repoid>-<suite>[-rollback<n>]' (HTTP 400 Bad request syntax or unsupported method)

    >>> Dist("squeeze--stable")  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    util.HTTPBadRequest: Malformed distribution 'squeeze--stable': Must be '<codename>-<repoid>-<suite>[-rollback<n>]' (HTTP 400 Bad request syntax or unsupported method)

    >>> Dist("squeeze-test-stable-")  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    util.HTTPBadRequest: Malformed distribution 'squeeze-test-stable-': Must be '<codename>-<repoid>-<suite>[-rollback<n>]' (HTTP 400 Bad request syntax or unsupported method)

    >>> Dist("squeeze-test-stable-rollback")  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    util.HTTPBadRequest: Malformed distribution 'squeeze-test-stable-rollback': Must be '<codename>-<repoid>-<suite>[-rollback<n>]' (HTTP 400 Bad request syntax or unsupported method)

    >>> Dist("squeeze-test-stable-rolback0")  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    util.HTTPBadRequest: Malformed distribution 'squeeze-test-stable-rolback0': Must be '<codename>-<repoid>-<suite>[-rollback<n>]' (HTTP 400 Bad request syntax or unsupported method)
    """

    _REGEX = re.compile(r"^\w+-\w+-\w+?(-rollback\d+)?$")

    def __init__(self, diststr):
        if not self._REGEX.match(diststr):
            raise util.HTTPBadRequest(f"Malformed distribution '{diststr}': Must be '<codename>-<repoid>-<suite>[-rollback<n>]'")

        self.diststr = diststr
        self._dsplit = self.diststr.split("-")
        self.codename = self._dsplit[0]
        self.repository = self._dsplit[1]
        self.suite = self._dsplit[2]
        self.is_rollback = len(self._dsplit) == 4
        self.rollback = self._dsplit[3] if self.is_rollback else None
        self.rollback_no = int(re.sub(r"\D", "", self.rollback)) if self.rollback else None

    def get(self, rollback=True):
        return "-".join(self._dsplit) if rollback else "-".join(self._dsplit[:3])


if __name__ == "__main__":
    for DI in [DebianDistroInfo(), UbuntuDistroInfo()]:
        for C in DI.all:
            print(Codename(C))
    print(setup_origins())
    print(setup_codenames())
    print(setup_codenames_from_origin("Debian"))
    print(setup_codenames_from_origin("Debian", "all"))
    print(setup_codenames_from_origin("Debian", "lts"))
    print(di_codenames())

    C = Codename("jdaskljk")
    CL = [Codename(C) for C in DebianDistroInfo().all]
    print([f"{C.codename} {C.cmpversion}" for C in sorted(CL + [C])])
    CL = [Codename(C) for C in UbuntuDistroInfo().all]
    print([f"{C.codename} {C.cmpversion}" for C in sorted(CL + [C])])
