#!/usr/bin/env bash
# Release helpers for GitLab CI.
set -euo pipefail

VERSION_REGEX='^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$'

normalize_version() {
  echo "${1#v}"
}

is_valid_version_tag() {
  [[ "$1" =~ $VERSION_REGEX ]]
}

# True if $1 is strictly greater than $2 (semver X.Y.Z).
is_newer_version() {
  local a b
  a="$(normalize_version "$1")"
  b="$(normalize_version "$2")"
  [[ "$a" != "$b" ]] && [[ "$(printf '%s\n' "$a" "$b" | sort -V | tail -n1)" == "$a" ]]
}

write_version_env() {
  local version="$1"
  local tag="$2"
  {
    echo "VERSION=${version}"
    echo "TAG=${tag}"
  } > version.env
}

validate() {
  local tag="${CI_COMMIT_TAG:?CI_COMMIT_TAG is required}"
  local version newest

  if ! is_valid_version_tag "$tag"; then
    echo "ERROR: Tag '${tag}' has an invalid format."
    echo "Expected: v1.7.0, 1.7.10, 1.8.0, ..."
    exit 1
  fi

  version="$(normalize_version "$tag")"
  echo "Validated release tag: ${tag} (version ${version})"

  mapfile -t tags < <(
    git tag -l \
      | grep -E "$VERSION_REGEX" \
      | grep -vxF "$tag" \
      || true
  )

  if ((${#tags[@]} == 0)); then
    echo "No previous release tags found; accepting ${version} as first release."
    write_version_env "$version" "$tag"
    return 0
  fi

  newest="$(printf '%s\n' "${tags[@]}" | sed 's/^v//' | sort -V | tail -n1)"
  echo "Previous release version: ${newest}"

  if ! is_newer_version "$version" "$newest"; then
    echo "ERROR: Release version ${version} is not greater than previous release ${newest}."
    exit 1
  fi

  write_version_env "$version" "$tag"
  echo "Version check passed: ${version} > ${newest}"
}

bump_files() {
  local version="${1:?version required}"

  sed -i "s/^version = \".*\"/version = \"${version}\"/" build.gradle.kts
  sed -i -E "s/^version: ['\"]?[0-9]+\.[0-9]+\.[0-9]+['\"]?/version: ${version}/" \
    src/main/resources/plugin.yml
  sed -i "1s/.*/# CopperKeys ${version}/" README.md
  sed -i -E "s/CopperKeys [0-9]+\.[0-9]+\.[0-9]+ enabled/CopperKeys ${version} enabled/" \
    src/main/java/nl/timfalken/copperkeys/CopperKeysPlugin.java

  echo "Updated project files to version ${version}"
}

require_push_token() {
  if [[ -n "${CI_PUSH_TOKEN:-}" ]]; then
    return 0
  fi

  cat <<'EOF' >&2
ERROR: CI_PUSH_TOKEN is not available in this job.

The variable may exist in Settings → CI/CD → Variables but still be hidden here if:
  1. It is Protected, while this tag/branch is not protected
     → Protect tag pattern (e.g. *) or uncheck Protected on the variable
  2. Its Environment scope is not "*"
  3. The key is misspelled (must be exactly CI_PUSH_TOKEN)

EOF
  exit 1
}

bump_and_push() {
  local version="${1:?version required}"
  local tag="${2:?tag required}"
  local token branch

  require_push_token
  token="${CI_PUSH_TOKEN}"
  branch="${CI_DEFAULT_BRANCH:?CI_DEFAULT_BRANCH is required}"

  git config user.email "gitlab-ci@${CI_SERVER_HOST:-gitlab.com}"
  git config user.name "GitLab CI"

  bump_files "$version"

  # Stage only versioned project files (never CI artifacts like version.env).
  git add -- \
    build.gradle.kts \
    src/main/resources/plugin.yml \
    README.md \
    src/main/java/nl/timfalken/copperkeys/CopperKeysPlugin.java

  if git diff --cached --quiet; then
    echo "No version file changes to commit (already at ${version})."
  else
    git commit -m "chore: bump version to ${version}"
  fi

  git remote set-url origin "https://oauth2:${token}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"

  # Push version bump only. Protected tags cannot be moved/updated.
  # Push may fail (token/branch ACL); the bumped files still flow to later jobs via artifacts.
  if git push origin "HEAD:refs/heads/${branch}" -o ci.skip; then
    echo "Pushed version bump for ${tag} to ${branch} (ci.skip). Tag left unchanged."
  else
    echo "WARNING: Could not push version bump to ${branch}; continuing with local bump for this pipeline."
    echo "WARNING: Master will catch up on a later successful bump push."
  fi
}

upload_file() {
  local file="$1"
  local package_url="$2"

  if [[ ! -f "$file" ]]; then
    echo "ERROR: Expected file not found: ${file}"
    return 1
  fi

  curl --fail --show-error --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
    --upload-file "$file" \
    "$package_url"

  echo "Uploaded ${file}"
  echo "  -> ${package_url}"
}

upload_package() {
  local version="${1:?version required}"
  local jar="build/libs/CopperKeys-${version}.jar"
  local pack="build/dist/CopperKeys-resourcepack-${version}.zip"
  local base_url package_jar_url package_pack_url

  if [[ ! -f "$jar" ]]; then
    echo "ERROR: Expected jar not found: ${jar}"
    ls -la build/libs/ || true
    exit 1
  fi
  if [[ ! -f "$pack" ]]; then
    echo "ERROR: Expected resource pack zip not found: ${pack}"
    ls -la build/dist/ || true
    exit 1
  fi

  base_url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/copperkeys/${version}"
  package_jar_url="${base_url}/CopperKeys-${version}.jar"
  package_pack_url="${base_url}/CopperKeys-resourcepack-${version}.zip"

  upload_file "$jar" "$package_jar_url"
  upload_file "$pack" "$package_pack_url"

  {
    echo "PACKAGE_URL=${package_jar_url}"
    echo "RESOURCE_PACK_URL=${package_pack_url}"
  } > package.env
}

# Self-rotate CI_PUSH_TOKEN and write the new value back to the CI/CD variable.
# Requires scopes: write_repository + self_rotate (or api), and api to update variables.
# Project access token role should be Maintainer (needed to edit CI/CD variables).
rotate_push_token() {
  local old_token expires_at response new_token var_meta protected masked raw scope

  require_push_token
  old_token="${CI_PUSH_TOKEN}"

  expires_at="$(date -u -d '+365 days' +%Y-%m-%d)"
  echo "Rotating CI_PUSH_TOKEN (new expiry ${expires_at})..."

  response="$(curl --fail --silent --show-error \
    --request POST \
    --header "PRIVATE-TOKEN: ${old_token}" \
    --header "Content-Type: application/json" \
    --data "{\"expires_at\":\"${expires_at}\"}" \
    "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/access_tokens/self/rotate")"

  new_token="$(jq -er '.token' <<<"${response}")"
  if [[ -z "${new_token}" || "${new_token}" == "null" ]]; then
    echo "ERROR: Token rotation response did not include a new token."
    echo "${response}"
    exit 1
  fi

  var_meta="$(curl --fail --silent --show-error \
    --header "PRIVATE-TOKEN: ${new_token}" \
    "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN")"

  protected="$(jq -r '.protected' <<<"${var_meta}")"
  masked="$(jq -r '.masked' <<<"${var_meta}")"
  raw="$(jq -r '.raw // false' <<<"${var_meta}")"
  scope="$(jq -r '.environment_scope // "*"' <<<"${var_meta}")"

  curl --fail --silent --show-error \
    --request PUT \
    --header "PRIVATE-TOKEN: ${new_token}" \
    --form "value=${new_token}" \
    --form "protected=${protected}" \
    --form "masked=${masked}" \
    --form "raw=${raw}" \
    --form "environment_scope=${scope}" \
    "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN" \
    >/dev/null

  echo "CI_PUSH_TOKEN rotated and CI/CD variable updated."
}

case "${1:-}" in
  validate) validate ;;
  bump)
    # shellcheck disable=SC1091
    source version.env
    bump_and_push "$VERSION" "$TAG"
    ;;
  upload)
    # shellcheck disable=SC1091
    source version.env
    upload_package "$VERSION"
    ;;
  rotate-token) rotate_push_token ;;
  *)
    echo "Usage: $0 {validate|bump|upload|rotate-token}"
    exit 1
    ;;
esac
