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

SCRIPT_NAME=$(basename "$0")

# Find README: check installed location first, then development location
if [[ -f "/usr/share/doc/compiletools/README.${SCRIPT_NAME}.rst" ]]; then
    README_PATH="/usr/share/doc/compiletools/README.${SCRIPT_NAME}.rst"
else
    README_PATH="$(dirname "$(readlink -f "$0")")/../src/compiletools/README.${SCRIPT_NAME}.rst"
fi

show_help() {
    echo "Usage: ${SCRIPT_NAME} {major|minor|patch}"
    echo ""
    if [[ -f "$README_PATH" ]]; then
        cat "$README_PATH"
    else
        echo "No documentation available for ${SCRIPT_NAME}"
        echo "See: https://github.com/drgeoffathome/compiletools"
    fi
    exit 0
}

for arg in "$@"; do
    case "$arg" in
        --help|-h) show_help ;;
    esac
done

# Ensure required tools exist
require_cmd() {
    command -v "$1" >/dev/null 2>&1 || { echo "Error: required tool not found: $1" >&2; exit 1; };
}
require_cmd git
require_cmd bump-my-version
require_cmd uv

# Check for gh (optional but recommended)
HAS_GH=false
if command -v gh >/dev/null 2>&1; then
    HAS_GH=true
else
    echo "Warning: 'gh' (GitHub CLI) not found. GitHub release notes will not be created." >&2
    # Suggest install command based on OS
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        case "$ID" in
            fedora|rhel|centos|rocky|alma)
                install_cmd="sudo dnf install gh" ;;
            debian|ubuntu|pop)
                install_cmd="sudo apt install gh" ;;
            arch|manjaro)
                install_cmd="sudo pacman -S github-cli" ;;
            opensuse*)
                install_cmd="sudo zypper install gh" ;;
            *)
                install_cmd="See https://github.com/cli/cli/blob/trunk/docs/install_linux.md" ;;
        esac
    elif [[ "$(uname)" == "Darwin" ]]; then
        install_cmd="brew install gh"
    else
        install_cmd="See https://github.com/cli/cli#installation"
    fi
    read -rp "Continue without GitHub release notes? [y/N] " answer
    if [[ "${answer,,}" != "y" ]]; then
        echo "Install gh with: $install_cmd" >&2
        exit 1
    fi
fi

#
# Bump the version of the vanilla compiletools repo and git push the tags
# Usage: ct-release {major|minor|patch}
# Examples:
#   ct-release patch    # e.g. 1.2.3 -> 1.2.4
#   ct-release minor    # e.g. 1.2.3 -> 1.3.0
#   ct-release major    # e.g. 1.2.3 -> 2.0.0
#

# Auto-detect the repo root from the script's own location.
# scripts/ sits directly under the repo root, so step one level up.
SCRIPT_DIR=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
DERIVED=$(cd "$SCRIPT_DIR/.." && pwd)
if [[ -f "$DERIVED/pyproject.toml" ]]; then
    ctdd="$DERIVED"
else
    ctdd=$(git rev-parse --show-toplevel 2>/dev/null) || {
        echo "Error: cannot determine repo root; run from within the compiletools repo." >&2
        exit 1
    }
fi

if [[ ! -d "$ctdd" ]]; then
    echo "Error: repo directory not found: $ctdd" >&2
    exit 1
fi

# Increase the version number in all files and push to github
pushd "$ctdd" >/dev/null

# Ensure working tree is clean
if ! git diff-index --quiet HEAD --; then
    echo "Error: working tree has uncommitted changes. Commit or stash before releasing." >&2
    popd >/dev/null
    exit 1
fi

# Enforce releasing only from master
branch=$(git rev-parse --abbrev-ref HEAD)
if [[ "$branch" != "master" ]]; then
    echo "Error: releases must be made from 'master' (current: $branch)" >&2
    popd >/dev/null
    exit 1
fi

# Parse and validate bump level
bump_level=${1:-}
if [[ -z "$bump_level" ]]; then
    echo "Usage: $0 {major|minor|patch}" >&2
    popd >/dev/null
    exit 1
fi
case "$bump_level" in
    major|minor|patch) ;;
    *)
        echo "Error: invalid bump level: $bump_level. Use major|minor|patch." >&2
        popd >/dev/null
        exit 1
        ;;
esac

# Refuse consecutive bump commits but continue with publish
bumpcount=$(git log --pretty=oneline -1 | grep -c Bump || true)
if [[ "$bumpcount" -eq 1 ]]; then
    echo "Warning: last commit was a version bump; skipping version bump." >&2
else
    # Perform the bump
    bump-my-version bump "$bump_level"
    git push
    git push --tags
    echo Pausing to give github time to generate the archive
    sleep 20
fi

# Use exact-match to ensure HEAD is tagged
tag=$(git describe --tags --exact-match)
popd >/dev/null

# Create a GitHub release with auto-generated notes
if [[ "$HAS_GH" == "true" ]]; then
    # Derive the owner/repo from the git remote so gh works without a default repo
    GH_REPO=$(git -C "$ctdd" remote get-url origin | sed -E 's#.+github\.com[:/]##; s/\.git$//')
    gh release create "$tag" --repo "$GH_REPO" --title "$tag" --generate-notes
else
    echo "No GitHub release notes generated (gh not available)."
fi

#Strip the v off the tag to get the numeric version
version=${tag#*v}

# Use pyp2rpm to create a RPM
# The following is now actively deprecated
# Pull a tarball from github and put it into SOURCES
#
#rpmhome=$(rpm --eval %_topdir)
#pushd "$rpmhome" >/dev/null
#tarball=${tag}.tar.gz
#while [[ ! -s "SOURCES/${tarball}" ]]; do
#    curl -L "https://github.com/DrGeoff/compiletools/archive/${tarball}" -o "SOURCES/${tarball}"
#done

# Create rpms of python-compiletools
#rpmbuild -ta SOURCES/${tarball}

#popd >/dev/null

# Build and push to PyPI using UV from the repo directory
pushd "$ctdd" >/dev/null
rm -rf dist build *.egg-info || true
uv build
# Example ~/.pypirc for token-based PyPI auth:
# [distutils]
# index-servers = pypi
# [pypi]
# repository = https://upload.pypi.org/legacy/
# username = __token__
# password = pypi-<your-token>
# (recommended: chmod 600 ~/.pypirc)
# Publish to PyPI using uv (check PyPI Simple API to avoid re-upload conflicts)
uv publish --token "$PYPI_API_TOKEN" --check-url https://pypi.org/simple
popd >/dev/null
