#!/bin/bash
# bin/bump-version.sh — auto-increment version in YAML frontmatter
# Usage:
#   bin/bump-version.sh <file>           # bump patch (default)
#   bin/bump-version.sh <file> --patch   # bump patch
#   bin/bump-version.sh <file> --minor   # bump minor, reset patch
#   bin/bump-version.sh <file> --major   # bump major, reset minor+patch
#
# Reads YAML frontmatter, increments version, updates `updated` field.
# Writes back in-place.

set -e

FILE="$1"
BUMP="${2:---patch}"

if [ -z "$FILE" ]; then
  echo "Usage: $0 <file> [--patch|--minor|--major]" >&2
  exit 1
fi

if [ ! -f "$FILE" ]; then
  echo "File not found: $FILE" >&2
  exit 1
fi

# Extract version
CURRENT=$(head -20 "$FILE" | grep -E '^version:' | head -1 | sed 's/version: *//; s/"//g')
if [ -z "$CURRENT" ]; then
  echo "No version field in frontmatter" >&2
  exit 1
fi

# Parse semver
IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT"

case "$BUMP" in
  --major)
    MAJOR=$((MAJOR + 1))
    MINOR=0
    PATCH=0
    ;;
  --minor)
    MINOR=$((MINOR + 1))
    PATCH=0
    ;;
  --patch|*)
    PATCH=$((PATCH + 1))
    ;;
esac

NEW_VERSION="$MAJOR.$MINOR.$PATCH"
TODAY=$(date +%Y-%m-%d)

# Replace in file (in-place)
sed -i.bak \
  -e "s|^version:.*|version: \"$NEW_VERSION\"|" \
  -e "s|^updated:.*|updated: \"$TODAY\"|" \
  "$FILE"

rm -f "$FILE.bak"

echo "$FILE: $CURRENT -> $NEW_VERSION (updated: $TODAY)"
