import hudson.plugins.git.ApiTokenPropertyConfiguration
import hudson.Util
import java.nio.charset.StandardCharsets
import java.security.MessageDigest


def entries = [
  [env: 'GIT_NOTIFY_TOKEN_BSTEIN_DEV_HOME', name: 'gitea-bstein-dev-home'],
]

entries.each { entry ->
  def token = System.getenv(entry.env)
  if (!token || token.trim().isEmpty()) {
    println("Git notifyCommit token ${entry.env} missing; skipping")
    return
  }

  try {
    def config = ApiTokenPropertyConfiguration.get()
    if (config.hasMatchingApiToken(token)) {
      println("Git notifyCommit token ${entry.name} already configured")
      return
    }

    def digest = MessageDigest.getInstance("SHA-256")
    def hash = Util.toHexString(digest.digest(token.getBytes(StandardCharsets.US_ASCII)))

    def field = ApiTokenPropertyConfiguration.class.getDeclaredField("apiTokens")
    field.setAccessible(true)
    def tokens = field.get(config)

    def ctor = ApiTokenPropertyConfiguration.HashedApiToken.class.getDeclaredConstructor(String.class, String.class)
    ctor.setAccessible(true)
    tokens.add(ctor.newInstance(entry.name, hash))
    config.save()

    println("Added git notifyCommit access token ${entry.name}")
  } catch (Throwable e) {
    println("Failed to configure git notifyCommit token ${entry.name}: ${e.class.simpleName}: ${e.message}")
  }
}
