#!/usr/bin/python3
# SPDX-License-Identifier: GPL-3.0+
# (GNU General Public License, version 3 or later at your convenience)
# Copyright 2026-2026 Nicolas Boulenguez <nicolas@debian.org>
"""Track deprecated Ada Library Info hashes in a Debian suite
and prepare a non-maintainer upload request updating them.

The first argument is the intended suite, the remaining ones
libFOO-dev-HASH or gnat-VERSION-HASH.
Example: debian/ada/deprecate_hash experimental gnat-16-c8fdaa46

Requires python3-apt.
"""
# black  deprecate_hash
# pylint deprecate_hash
# mypy   deprecate_hash

import functools
import re
import sys
import subprocess
import typing

import apt.package

APT_CACHE = apt.Cache()
GNU_TYPE = subprocess.check_output(
    args=("dpkg-architecture", "-qDEB_BUILD_GNU_TYPE"), encoding="ascii"
).rstrip()
SUITE = sys.argv[1]


# Cache the result because a -dev package may depend on several
# vanished virtual packages.
@functools.cache
def virtual_from_version(version: apt.package.Version) -> str:
    """In most cases, the argument is libNAME-dev, and the result is
    the libNAME-dev-HASH virtual package provided by it.

    When version is gnat-VERSION, the result is gnat-VERSION-HASH
    provided by gnat-VERSION-GNU_TRIPLET."""
    name = version.package.name
    if name.startswith("l"):
        vsn = version
    else:
        vsn = version_from_name(f"{name}-{GNU_TYPE.replace('_', '-')}")
    regex = re.compile(rf"{re.escape(name)}-[0-9a-f]{{8}}")
    for virtual in vsn.provides:
        if regex.fullmatch(virtual):
            return virtual
    assert False, f"{name} provides no hash"


# Cache the result because a -dev package may depend on several
# vanished virtual packages.
@functools.cache
def version_from_name(package_name: str) -> apt.package.Version:
    """Select the version of the -dev package in SUITE.

    The argument is either libNAME-dev or gnat-VERSION."""
    in_unstable = None
    for v in APT_CACHE[package_name].versions:
        for o in v.origins:
            if o.archive == SUITE:
                return v
            if o.archive == "unstable":
                in_unstable = v
    if SUITE == "experimental" and in_unstable:
        return in_unstable
    assert False, f"no version of {package_name} in {SUITE}"


@functools.cache
def reverse_depends(virtual: str) -> typing.Iterator[apt.package.Version]:
    "Return the lib*-dev packages depending on {libNAME-dev,gnat-VERSION}-HASH"
    args = ("apt-cache", "showpkg", virtual)
    out = subprocess.check_output(args, encoding="ascii")
    m = re.search(r"\nReverse Depends: ((?:\n .*)*)", out)
    assert m, f"no Reverse Depends in {out}"
    for m in re.finditer(r" *(lib[a-z0-9+.-]+-dev),", m[1]):
        yield version_from_name(m[1])


class DependencyWait(typing.NamedTuple):
    """If 'vanished' is None, the build should require the 'after' version
    (mostly for information).

    If 'vanished' is provided (on the command line), a strictly
    superior version is required.
    """

    dev_pkg: apt.package.Version  # libNAME-dev or gnat-VERSION
    vanished: str | None  # from the command line, or  None


nmus = dict[str, set[DependencyWait]]()
# "foo_1-2": {(libbar-dev=3-4, None),
#             (libmoo-dev=5-6, None),
#             (libbaz-dev=7-8, "libbaz-dev-1a2b3c4d")}
# nmu foo_1-2 . ANY . -m 'Rebuild with baz_7-8'
#  dw foo_1-2 . ANY . -m 'libbar-dev (>> 3-4)'
#  # 3-4 provides 5e6f7a8b but won't after the NMUs
#  dw foo_1-2 . ANY . -m 'libbaz-dev (>= 7-8)'
#  # 7-8 provides 1a2b3c4d instead of 3c4d1a2b previously


def find_rdeps(dw: DependencyWait) -> None:
    "Find transitive reverse dependencies."
    if dw.vanished:
        virtual = dw.vanished
        cumulative = set()
    else:
        virtual = virtual_from_version(dw.dev_pkg)
        cumulative = nmus[f"{dw.dev_pkg.source_name}_{dw.dev_pkg.source_version}"]

    for rdep in reverse_depends(virtual):
        # print(f"{dw.dev_pkg.package.name}->{rdep.package.name}")
        rdep_src = f"{rdep.source_name}_{rdep.source_version}"
        rdep_dws = nmus.setdefault(rdep_src, set())
        rdep_dws.update(cumulative)
        rdep_dws.add(dw)
        find_rdeps(DependencyWait(rdep, None))


def main() -> None:
    """List Debian non maintainer uploads caused by a change in an Ada library.

    For Ada libraries, libNAME-dev Provides: libNAME-dev-HASH, where
    HASH depends on the Ada sources.  This command is useful when an
    upload changes the Ada sources, hence the HASH component in the
    virtual package name.

    As a special case, gnat-VERSION-{GNU_TYPE with dashes instead of
    underscores_ provides gnat-VERSION-HASH for the language library.
    For convenience, we consider that the -dev package is
    gnat-VERSION, and only add GNU_TYPE when necessary.  gnat-VERSION
    and gnat-VERSION-GNU_TRIPLET are both Arch: any.  They share the
    same source and version.

    The arguments are the name of the suite, usually 'stable',
    'unstable' or 'experimental', then vanished virtual packages.

    When the suite is experimental, binary packages not found are
    searched in unstable.
    """
    print(
        f"""To: Debian Bug Tracking System <submit@bugs.debian.org>
Subject: gnat: please rebuild Ada packages in {SUITE}

Package: release.debian.org
Severity: normal
User: release.debian.org@packages.debian.org
Usertags: binnmu

Dear release team

Some packages became uninstallable in {SUITE} because
"""
    )
    for vanished in sys.argv[2:]:
        dev_pkg = version_from_name(vanished[:-9])
        find_rdeps(DependencyWait(dev_pkg, vanished))
        print(f"  {dev_pkg.package.name} stopped providing {vanished}")
    print(
        """
The issue is specific to Ada. Each -dev package provides a virtual
package named after a HASH of the sources.  When the sources change,
all transitive reverse dependencies of the removed virtual packages
must be rebuilt in topological order.

Would you please schedule the binary NMUs in the list below?  I can
provide the python script generating it.

It includes all transitive dependencies because this was easyer and
may help the dependency resolvers.

The dw restrictions use >> for NMUed -dev packages, and >= for the
already uploaded -dev package(s) triggering the NMUs, in case some
architectures are not up-to-date.

The standard library, built by gcc-VERSION, does not use the
libgnat-dev scheme. The sources are in gnat-VERSION-GNU_TYPE and
gnat-VERSION provides gnat-VERSION-HASH. gnat-VERSION has a strict
dependency on gnat-VERSION-GNU_TYPE so that only affects details here.
"""
    )
    suite = "" if SUITE == "unstable" else f" {SUITE} ."
    for s in sorted(nmus.keys()):
        dws = sorted(nmus[s])
        roots = (f"{d.source_name}_{d.source_version}" for d, v in dws if v)
        print(f"nmu {s:<30} . ANY .{suite} -m 'Rebuild with {' '.join(roots)}'")
        for d, v in sorted(dws):
            op = ">=" if v else ">>"
            dw = f"{d.package.name:<20} ({op} {d.version})"
            print(f" dw {s:<30} . ANY .{suite} -m '{dw}'")


main()
