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

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 <name> <version>" >&2
  exit 2
fi

NAME="$1"
VERSION="$2"

if [ ! -f setup.py ]; then
  echo "setup.py not found in current directory" >&2
  exit 3
fi

./.venv/bin/python3 - "$NAME" "$VERSION" <<'PY'
import re
import sys

name = sys.argv[1]
version = sys.argv[2]

with open("setup.py", "r", encoding="utf-8") as fh:
  content = fh.read()

content = re.sub(r"name\s*=\s*['\"]([^'\"]+)['\"]", f"name='{name}'", content, count=1)
content = re.sub(r"version\s*=\s*['\"]([^'\"]+)['\"]", f"version='{version}'", content, count=1)

with open("setup.py", "w", encoding="utf-8") as fh:
  fh.write(content)

with open("src/catnose/__init__.py", "r", encoding="utf-8") as fh:
  content = fh.read()

content = re.sub(r'__version__\s*=\s*["\']([^"\']+)["\']', f'__version__ = "{version}"', content)

with open("src/catnose/__init__.py", "w", encoding="utf-8") as fh:
  fh.write(content)

with open("pyproject.toml", "r", encoding="utf-8") as fh:
  content = fh.read()

content = re.sub(r'(?m)^version\s*=\s*["\']([^"\']+)["\']', f'version = "{version}"', content)

with open("pyproject.toml", "w", encoding="utf-8") as fh:
  fh.write(content)
PY

rm -rf dist build *.egg-info
./.venv/bin/python3 -m build
./.venv/bin/python3 -m twine upload "dist/${NAME}-${VERSION}.tar.gz" "dist/${NAME}-${VERSION}-py3-none-any.whl"
