import hudson.model.User
import jenkins.security.ApiTokenProperty

def userId = (System.getenv("ARIADNE_JENKINS_API_USER") ?: "").trim()
def envTokenValue = (System.getenv("ARIADNE_JENKINS_API_TOKEN") ?: "").trim()
def tokenName = "ariadne-weather"
def tokenFile = new File("/var/jenkins_home/secrets/ariadne-api-token")
def userFile = new File("/var/jenkins_home/secrets/ariadne-api-user")
def persistedTokenValue = tokenFile.exists() ? (tokenFile.text ?: "").trim() : ""
def tokenValue = envTokenValue ?: persistedTokenValue

if (!userId || !tokenValue) {
  println("Ariadne API user bootstrap skipped: missing ARIADNE_JENKINS_API_USER and no token source available")
  return
}

def user = User.getById(userId, true)
if (user == null) {
  println("Ariadne API user bootstrap failed: unable to resolve user ${userId}")
  return
}

if (!user.getFullName() || user.getFullName().trim() == userId) {
  user.setFullName("Ariadne Metrics")
}

def prop = user.getProperty(ApiTokenProperty.class)
if (prop == null) {
  prop = new ApiTokenProperty()
  user.addProperty(prop)
}

if (persistedTokenValue && prop.matchesPassword(persistedTokenValue)) {
  tokenValue = persistedTokenValue
}

if (!prop.matchesPassword(tokenValue)) {
  def store = prop.getTokenStore()

  boolean configured = false
  try {
    def existing = store.getTokenListSortedByName().find { token ->
      try {
        token.getName() == tokenName
      } catch (Throwable ignored) {
        false
      }
    }

    if (existing != null) {
      try {
        store.revokeToken(existing.getUuid())
      } catch (Throwable ignored) {
        try {
          store.revokeToken(existing.uuid)
        } catch (Throwable ignoredAgain) {
          println("Ariadne API user bootstrap warning: failed to revoke existing token ${tokenName}")
        }
      }
    }

    store.addFixedNewToken(tokenName, tokenValue)
    configured = true
  } catch (Throwable ignored) {
    // Fallback for older token-store variants.
  }

  if (!configured) {
    if (persistedTokenValue && prop.matchesPassword(persistedTokenValue)) {
      tokenValue = persistedTokenValue
    } else {
      def generated = store.generateNewToken(tokenName)
      if (generated?.plainValue) {
        tokenValue = generated.plainValue
      }
      println("Ariadne API user bootstrap warning: addFixedNewToken unavailable, generated replacement token")
    }
  }
}

tokenFile.parentFile?.mkdirs()
tokenFile.text = tokenValue + "\n"
tokenFile.setReadable(false, false)
tokenFile.setReadable(true, true)
tokenFile.setWritable(false, false)
tokenFile.setWritable(true, true)

userFile.parentFile?.mkdirs()
userFile.text = userId + "\n"
userFile.setReadable(false, false)
userFile.setReadable(true, true)
userFile.setWritable(false, false)
userFile.setWritable(true, true)

user.save()
println("Ariadne API user bootstrap complete for ${userId}")
