#!/usr/bin/env python3

import os
import re
from pathlib import Path

basedir = Path(__file__).parent
resourcesdir = Path('src/test/resources/com/android/apksig')
sourcedir = Path(basedir / '../../src/test/java/com/android/apksig')
source = (sourcedir / 'ApkVerifierTest.java').read_text()

os.chdir(basedir.parent.parent)

sdk_nums = {
    'AndroidSdkVersion.N': 24,
    'AndroidSdkVersion.P': 28,
}

with open(basedir / 'ApkVerifierTest.sh', 'w') as fp:
    fp.write("""#!/bin/sh -e
set -x

# test -J args from apksigner shell script
apksigner -JXmx256M verify src/test/resources/com/android/apksig/v1-only-with-rsa-pkcs1-sha384-1.2.840.113549.1.1.1-1024.apk

""")

    for m in sorted(
        set(
            re.findall(
                r'''assertVerifiedForEach\(\s*"([^"]+)"''', source, flags=re.DOTALL
            )
        )
    ):
        for f in sorted(resourcesdir.glob(m.replace("%s", "*"))):
            fp.write(f"apksigner verify {f}\n")

    for f, msv in re.findall(r'''assertVerified\(\s*verifyForMinSdkVersion\(\s*"([^"]+)",\s*([^)]*)''', source, flags=re.DOTALL):
        print(f, msv)
        try:
            msv = int(msv)
        except ValueError as e:
            msv = sdk_nums[msv]
        fp.write(f"apksigner verify --min-sdk-version {msv} {str(resourcesdir)}/{f}\n")

    for f, msv in re.findall(r'''assertVerificationFailure\(\s*verifyForMinSdkVersion\(\s*"([^"]+)",\s*([^)]*)''', source, flags=re.DOTALL):
        print(f, msv)
        try:
            msv = int(msv)
        except ValueError as e:
            msv = sdk_nums[msv]
        fp.write(f"! apksigner verify --min-sdk-version {msv} {str(resourcesdir)}/{f}\n")

    for f in re.findall(r'''assertVerificationFailure\(\s*"([^"]+)"''', source, flags=re.DOTALL):
        fp.write(f"! apksigner verify {str(resourcesdir)}/{f}\n")


# for f in `grep -A1 'assertVerificationFailure(' src/test/java/com/android/apksig/ApkVerifierTest.java \
#   | grep -Eo ' "v[12]-.*\.apk"' \
#   | sed -e 's,^ ",src/test/resources/com/android/apksig/,' -e 's,",,g'`; do
#     echo '! apksigner verify' $f  >> $basedir/debian/tests/ApkVerifierTest.sh
# done

    fp.write("echo SUCCESS\n")
