#!/usr/bin/env python3
"""Drop the dependencies a Linux build can never use from a vendored crate.

Cargo resolves a crate's dependencies for every platform, so the source of each
one has to be present even when no Linux build compiles it. The archive's own
librust-rustls-platform-verifier-dev is already stripped this way. Upstream's
0.7 is not in the archive, so it is vendored, and this script gives it the same
treatment. That keeps the Apple, Android and Windows bindings out of the
source package. security-framework ships documentation adapted from Apple
under the APSL, which Debian does not accept as DFSG-free.

Usage: trim-vendored-crate CRATE_DIR

Run by debian/vendor-crates on the vendor tree and by
debian/update-vendored-crates on the cargo-vendor output, so both agree on
which crates remain.
"""
import json
import os
import re
import sys

# The cfg() of every target-specific table a Linux build never selects.
DROP_CFGS = {
    'cfg(any(target_vendor = "apple"))',
    'cfg(target_arch = "wasm32")',
    'cfg(target_os = "android")',
    'cfg(windows)',
}
# Dependencies that only those tables, or optional features for them, use.
DROP_DEPS = ("jni", "webpki-root-certs", "android_logger")

TARGET_TABLE = re.compile(
    r"""^\[target\.(?:'([^']*)'|"([^"]*)")\.(?:dev-|build-)?dependencies\.[^\]]+\]""")
PLAIN_TABLE = re.compile(
    r"^\[(?:dev-|build-)?dependencies\.(?:%s)\]" % "|".join(map(re.escape, DROP_DEPS)))
FEATURE_ITEM = re.compile(
    r'^\s*"(?:dep:)?(?:%s)",?\s*$' % "|".join(map(re.escape, DROP_DEPS)))
# Whatever the rules above missed, in any table, must not be left behind.
FORBIDDEN = re.compile(
    r"(?m)^\[[^\]]*dependencies\.(?:security-framework(?:-sys)?|core-foundation(?:-sys)?"
    r"|jni|windows-sys|rustls-platform-verifier-android|webpki-root-certs|android_logger)\]")


def drop_section(header):
    target = TARGET_TABLE.match(header)
    if target:
        return (target.group(1) or target.group(2)) in DROP_CFGS
    return bool(PLAIN_TABLE.match(header))


def trim_manifest(text):
    kept = []
    for section in re.split(r"(?m)^(?=\[)", text):
        header = section.split("\n", 1)[0]
        if drop_section(header):
            continue
        if header == "[features]":
            section = "".join(line for line in section.splitlines(keepends=True)
                              if not FEATURE_ITEM.match(line))
        kept.append(section)
    return "".join(kept)


def trim_crate(crate_dir):
    name = os.path.basename(os.path.normpath(crate_dir))
    if not re.match(r"rustls-platform-verifier-\d", name):
        sys.exit("no trim rule for %s" % name)
    manifest = os.path.join(crate_dir, "Cargo.toml")
    with open(manifest, encoding="utf-8") as f:
        trimmed = trim_manifest(f.read())
    # A rule that no longer matches would silently keep the crates it exists to
    # drop, and an over-broad one would drop the Linux dependencies.
    if "rustls-native-certs]" not in trimmed:
        sys.exit("%s: the Linux certificate-store dependency is gone" % manifest)
    leftovers = FORBIDDEN.findall(trimmed)
    if leftovers:
        sys.exit("%s: non-Linux dependencies remain: %s" % (manifest, leftovers))
    with open(manifest, "w", encoding="utf-8") as f:
        f.write(trimmed)
    # The file list protects against accidental edits, and this is an
    # intentional one; keep the package hash, as debian/vendor-crates does.
    checksum = os.path.join(crate_dir, ".cargo-checksum.json")
    with open(checksum, encoding="utf-8") as f:
        data = json.load(f)
    data["files"] = {}
    with open(checksum, "w", encoding="utf-8") as f:
        json.dump(data, f)


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit(__doc__)
    trim_crate(sys.argv[1])
