#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"
cd "${REPO_ROOT}"

VERSION_FILE="./version"
PUBSPEC_FILE="./frontend/pweb/pubspec.yaml"
if [[ ! -f "${PUBSPEC_FILE}" && -f "./frontend/pweb/pubspec.yml" ]]; then
  PUBSPEC_FILE="./frontend/pweb/pubspec.yml"
fi

if [[ ! -f "${VERSION_FILE}" ]]; then
  echo "[bump-version] missing ${VERSION_FILE}" >&2
  exit 1
fi

if [[ ! -f "${PUBSPEC_FILE}" ]]; then
  echo "[bump-version] missing frontend pubspec file" >&2
  exit 1
fi

current_version="$(tr -d '[:space:]' < "${VERSION_FILE}")"
if [[ -z "${current_version}" ]]; then
  echo "[bump-version] ${VERSION_FILE} is empty" >&2
  exit 1
fi

new_version="$(printf '%s\n' "${current_version}" | awk -F. -v OFS=. '
  NF == 1 { print ++$NF; next }
  { $NF = sprintf("%0*d", length($NF), ($NF + 1)); print }
')"

current_pubspec_version="$(
  awk '/^version:[[:space:]]*/ {
    sub(/^version:[[:space:]]*/, "", $0)
    print
    exit
  }' "${PUBSPEC_FILE}"
)"

if [[ -z "${current_pubspec_version}" ]]; then
  echo "[bump-version] could not find version line in ${PUBSPEC_FILE}" >&2
  exit 1
fi

build_number=0
if [[ "${current_pubspec_version}" == *+* ]]; then
  build_number="${current_pubspec_version##*+}"
fi

if [[ ! "${build_number}" =~ ^[0-9]+$ ]]; then
  echo "[bump-version] invalid build number in ${PUBSPEC_FILE}: ${current_pubspec_version}" >&2
  exit 1
fi

next_build_number=$((build_number + 1))

version_tmp="${VERSION_FILE}.tmp.$$"
pubspec_tmp="${PUBSPEC_FILE}.tmp.$$"
cleanup() {
  rm -f "${version_tmp}" "${pubspec_tmp}"
}
trap cleanup EXIT INT TERM

printf '%s\n' "${new_version}" > "${version_tmp}"
awk -v version="${new_version}" -v build="${next_build_number}" '
  BEGIN { updated = 0 }
  /^version:[[:space:]]*/ && !updated {
    print "version: " version "+" build
    updated = 1
    next
  }
  { print }
  END {
    if (!updated) {
      exit 1
    }
  }
' "${PUBSPEC_FILE}" > "${pubspec_tmp}"

mv "${version_tmp}" "${VERSION_FILE}"
mv "${pubspec_tmp}" "${PUBSPEC_FILE}"

echo "===================================="
echo "Release version bumped"
echo "===================================="
echo "version: ${current_version} -> ${new_version}"
echo "${PUBSPEC_FILE}: ${current_pubspec_version} -> ${new_version}+${next_build_number}"
