name: Create tag

permissions:
  contents: write

on:
  workflow_dispatch:
    inputs:
      increment_type:
        type: choice
        description: Select the type of version increment
        required: true
        options:
          - patch
          - minor
          - major

jobs:
  increment_version:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - id: version
        name: Get current version
        run: |
          VERSION=$(git describe --abbrev=0 --tags)

          # Split version into major, minor, and patch
          MAJOR=$(echo $VERSION | awk -F '.' '{print $1}' | cut -c 2-)
          MINOR=$(echo $VERSION | awk -F '.' '{print $2}')
          PATCH=$(echo $VERSION | awk -F '.' '{print $3}')

          # Increment the appropriate part of the version
          if [[ ${{ inputs.increment_type }} == "patch" ]]; then
            PATCH=$((PATCH + 1))
          elif [[ ${{ inputs.increment_type }} == "minor" ]]; then
            MINOR=$((MINOR + 1))
            PATCH=0
          elif [[ ${{ inputs.increment_type }} == "major" ]]; then
            MAJOR=$((MAJOR + 1))
            MINOR=0
            PATCH=0
          fi

          # Update the version
          echo "NEW_VERSION=v$MAJOR.$MINOR.$PATCH" >> $GITHUB_OUTPUT

      - name: Create release
        uses: ncipollo/release-action@v1
        with:
          name: Meshtastic Protobufs ${{ steps.version.outputs.NEW_VERSION }}
          tag: ${{ steps.version.outputs.NEW_VERSION }}
          generateReleaseNotes: true
          token: ${{ github.token }}

      - name: Setup Buf
        uses: bufbuild/buf-action@v1.2.0
        with:
          github_token: ${{ github.token }}
          token: ${{ secrets.BUF_TOKEN }}
          setup_only: true

      - name: Push to schema registry
        env:
          BUF_TOKEN: ${{ secrets.BUF_TOKEN }}
        run: |
          buf push --tag ${{ steps.version.outputs.NEW_VERSION }}
