#!/usr/bin/env python3
"""Replace any development signature on an AAB with the upload key."""

from __future__ import annotations

import argparse
import subprocess
from pathlib import Path

from android_config import ConfigError, parse_properties


def run(command: list[str], *, allowed: set[int] | None = None) -> None:
    completed = subprocess.run(command, check=False)
    accepted = allowed or {0}
    if completed.returncode not in accepted:
        raise ConfigError(f"command failed with exit code {completed.returncode}: {command[0]}")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--bundle", required=True, type=Path)
    parser.add_argument("--properties", required=True, type=Path)
    parser.add_argument("--keystore", required=True, type=Path)
    args = parser.parse_args()

    try:
        values = parse_properties(args.properties)
        store_password = values["storePassword"]
        key_password = values["keyPassword"]
        key_alias = values["keyAlias"]
        if not args.bundle.is_file():
            raise ConfigError(f"bundle does not exist: {args.bundle}")
        for secret in (store_password, key_password):
            print(f"::add-mask::{secret}")
        run(
            [
                "zip",
                "-d",
                str(args.bundle),
                "META-INF/*.SF",
                "META-INF/*.RSA",
                "META-INF/*.DSA",
                "META-INF/*.EC",
                "META-INF/SIG-*",
            ],
            allowed={0, 12},
        )
        run(
            [
                "jarsigner",
                "-keystore",
                str(args.keystore),
                "-storepass",
                store_password,
                "-keypass",
                key_password,
                str(args.bundle),
                key_alias,
            ]
        )
        run(["jarsigner", "-verify", str(args.bundle)])
    except (ConfigError, KeyError, OSError) as exc:
        print(f"::error::{exc}")
        raise SystemExit(1) from exc
    print(f"Signed Android App Bundle: {args.bundle}")


if __name__ == "__main__":
    main()
