#!/usr/bin/env python3

from __future__ import annotations

import shutil
import subprocess
import sys
import tempfile
import unittest
import zipfile
from pathlib import Path


@unittest.skipUnless(
    shutil.which("keytool") and shutil.which("jarsigner") and shutil.which("zip"),
    "Java signing tools are unavailable",
)
class SignBundleIntegrationTest(unittest.TestCase):
    def test_signs_an_unsigned_bundle(self) -> None:
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            keystore = root / "upload.jks"
            bundle = root / "app-release.aab"
            properties = root / "android-signing.properties"
            password = "test-password"
            subprocess.run(
                [
                    "keytool",
                    "-genkeypair",
                    "-noprompt",
                    "-keystore",
                    str(keystore),
                    "-storepass",
                    password,
                    "-keypass",
                    password,
                    "-alias",
                    "upload",
                    "-keyalg",
                    "RSA",
                    "-dname",
                    "CN=CI Test",
                    "-validity",
                    "1",
                ],
                check=True,
                capture_output=True,
            )
            properties.write_text(
                "storePassword=test-password\n"
                "keyPassword=test-password\n"
                "keyAlias=upload\n"
            )
            with zipfile.ZipFile(bundle, "w") as archive:
                archive.writestr("base/manifest/AndroidManifest.xml", b"fixture")

            subprocess.run(
                [
                    sys.executable,
                    str(Path(__file__).with_name("sign_bundle.py")),
                    "--bundle",
                    str(bundle),
                    "--properties",
                    str(properties),
                    "--keystore",
                    str(keystore),
                ],
                check=True,
                capture_output=True,
            )

            verified = subprocess.run(
                ["jarsigner", "-verify", str(bundle)],
                check=False,
                capture_output=True,
                text=True,
            )
            self.assertEqual(verified.returncode, 0, verified.stderr)


if __name__ == "__main__":
    unittest.main()
