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

BUMP="${1:-}"
if [[ "$BUMP" != "patch" && "$BUMP" != "minor" && "$BUMP" != "major" ]]; then
    printf "Usage: %s <patch|minor|major>\n" "$0" >&2
    exit 1
fi

cd "$(git rev-parse --show-toplevel)"

CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [[ "$CURRENT_BRANCH" != "master" ]]; then
    printf "error: must be on master branch (currently on '%s')\n" "$CURRENT_BRANCH" >&2
    exit 1
fi

if ! git diff --quiet || ! git diff --staged --quiet; then
    printf "error: working tree is not clean; commit or stash changes first\n" >&2
    exit 1
fi

CURRENT=$(python3 -c "
import re, sys
with open('pyproject.toml') as f:
    content = f.read()
m = re.search(r'^version = \"(\d+\.\d+\.\d+)\"', content, re.MULTILINE)
if not m:
    sys.exit('error: could not find version in pyproject.toml')
print(m.group(1))
")

NEW=$(python3 -c "
major, minor, patch = map(int, '$CURRENT'.split('.'))
if '$BUMP' == 'major':
    major += 1; minor = 0; patch = 0
elif '$BUMP' == 'minor':
    minor += 1; patch = 0
else:
    patch += 1
print(f'{major}.{minor}.{patch}')
")

printf "Bumping %s → %s (%s)\n" "$CURRENT" "$NEW" "$BUMP"

# Rewrite in python3 rather than `sed -i`: BSD sed (macOS) reads the argument
# after -i as a backup suffix, so the GNU-style one-liner is not portable.
python3 - "$CURRENT" "$NEW" <<'PY'
import pathlib
import re
import sys

current, new = sys.argv[1], sys.argv[2]
targets = {
    "pyproject.toml": 'version = "{}"',
    "liteinfer/__init__.py": '__version__ = "{}"',
}

# Anchor at line start so a version pin nested elsewhere in the file is not hit.
for path, template in targets.items():
    file = pathlib.Path(path)
    content = file.read_text()
    old_line, new_line = template.format(current), template.format(new)
    pattern = re.compile("^" + re.escape(old_line) + "$", re.MULTILINE)
    if not pattern.search(content):
        sys.exit(f"error: could not find '{old_line}' in {path}")
    # A lambda replacement keeps re from interpreting escapes in the new version line.
    file.write_text(pattern.sub(lambda _match: new_line, content, count=1))
PY

git add pyproject.toml liteinfer/__init__.py
git commit -m "chore: release v${NEW}"
git tag "v${NEW}"

printf "\nDone. Run:  git push origin master --tags\n"
