name: Tag a new version
on:
  workflow_call:
    inputs:
      version:
        required: true
        type: string
    outputs:
      sha:
        description: "The SHA of the commit made which bumps the version"
        value: ${{ jobs.tag.outputs.sha }}
    secrets:
      BOT_GITHUB_TOKEN:
        required: true

jobs:
  tag:
    name: Tag a new version
    runs-on: ubuntu-24.04
    permissions:
      contents: write

    outputs:
      sha: ${{ fromJSON(steps.commit.outputs.result).commit }}

    steps:
      - name: Checkout the code
        uses: actions/checkout@v4.2.2

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Set the crates version
        env:
          VERSION: ${{ inputs.version }}
        run: |
          sed -i "s/^package.version = .*/package.version = \"$VERSION\"/" Cargo.toml
          sed -i "/path = \".\/crates\//s/version = \".*\"/version = \"=$VERSION\"/" Cargo.toml

      - name: Run `cargo metadata` to make sure the lockfile is up to date
        run: cargo metadata --format-version 1

      - name: Commit and tag using the GitHub API
        uses: actions/github-script@v7.0.1
        id: commit
        env:
          VERSION: ${{ inputs.version }}
        with:
          # Commit & tag with the actions token, so that they get signed
          # This returns the commit sha and the tag object sha
          script: |
            const script = require('./.github/scripts/commit-and-tag.cjs');
            return await script({ core, github, context });

      - name: Update the refs
        uses: actions/github-script@v7.0.1
        env:
          VERSION: ${{ inputs.version }}
          TAG_SHA: ${{ fromJSON(steps.commit.outputs.result).tag }}
          COMMIT_SHA: ${{ fromJSON(steps.commit.outputs.result).commit }}
        with:
          # Update the refs with the bot token, so that workflows are triggered
          github-token: ${{ secrets.BOT_GITHUB_TOKEN }}
          script: |
            const script = require('./.github/scripts/create-version-tag.cjs');
            await script({ core, github, context });
