#!/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}"
  local readme

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

  shopt -s nullglob
  for readme in src/README-*.md; do
    sed -i "1s/.*/# ContainerPipes ${version}/" "$readme"
    if [[ "$readme" != "src/README-${version}.md" ]]; then
      git mv "$readme" "src/README-${version}.md"
    fi
  done
  shopt -u nullglob

  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/containerpipes/ContainerPipesPlugin.java
  git add -A -- src/README-*.md 2>/dev/null || true

  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.
  git push origin "HEAD:refs/heads/${branch}" -o ci.skip

  echo "Pushed version bump for ${tag} to ${branch} (ci.skip). Tag left unchanged."
}

upload_package() {
  local version="${1:?version required}"
  local jar="build/libs/ContainerPipes-${version}.jar"
  local package_url

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

  package_url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/containerpipes/${version}/ContainerPipes-${version}.jar"
  curl --fail --show-error --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
    --upload-file "$jar" \
    "$package_url"

  echo "Uploaded ${jar}"
  echo "PACKAGE_URL=${package_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
