import subprocess
import sys
from pathlib import Path
from typing import Union

from dev_tools.build.sign.identity import SIGNING_IDENTITY_NAME
from dev_tools.build.utility import get_first_file_found


def sign_file_for_authenticity(*paths: Union[str, Path]):
    """
    Sign executables on windows, so security systems will see them less of a threat.
    """
    if sys.platform.startswith("win"):
        signtool = get_first_file_found(
            "signtool.exe", Path("C:/Program Files (x86)/Windows Kits/10/bin/10.0.19041.0/x64/signtool.exe")
        )
        args = [
            "sign",
            *["/tr", "http://timestamp.digicert.com"],
            *["/td", "sha256"],
            *["/fd", "sha256"],
            *["/n", SIGNING_IDENTITY_NAME],
        ]
        paths = [str(path) for path in paths]
        subprocess.check_call([signtool, *args, *paths])


# TODO: We can do this.. but should we?
# Java JAR signing:
# 1. create eToken.cfg in JAVA_HOME/bin
#   name=eToken
#   library=c:\WINDOWS\system32\eTPKCS11.dll
#
# check name of the key:
# keytool -list -keystore NONE -storetype PKCS11 -providerclass sun.security.pkcs11.SunPKCS11 -providerArg ./eToken.cfg
#
# use key name to sign jar:
# jarsigner -tsa http://timestamp.digicert.com -verbose -keystore NONE -storetype PKCS11
#  -providerclass sun.security.pkcs11.SunPKCS11 -providerArg ./eToken.cfg path-to-jar "Clarabot Zrt"
