---
name: Publish

on:
  # Only run the workflow for pushes to the default branch.
  push:
    branches:
      - main

  # Allow the workflow to be triggered manually from the Actions tab.
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Check for [skip publish]
        # TODO: github.event.commits is an array of all of the commits in the
        # pull request. I should look into whether or not there's an easy way to
        # use that here instead of relying on the flag to be used in the merge
        # commit. There might be a way to use github.event.commits as a matrix,
        # but that will probably cause all steps to run for each commit,
        # including the step that publishes the crate.
        if: contains(github.event.head_commit.message, '[skip publish]')
        run: |
          echo "[skip publish] found."
          exit 1

      - uses: dorny/paths-filter@v4
        id: changes
        with:
          filters: |
            src:
              - 'src/**'
            manifest:
              - 'Cargo.toml'

      - name: Check for releasable changes
        if: steps.changes.outputs.src == 'false' && steps.changes.outputs.manifest == 'false'
        run: |
          echo "No changes were made to relevant files."
          exit 1

      - name: Configure Git
        run: |
          git config user.email "github@github.com"
          git config user.name "GitHub Actions"

      - name: Set version number
        run: |
          count=$(git rev-list --count --branches --no-merges)
          now=$(date +"%Y %m")
          set $now
          year=$1
          month=$2
          let "month=10#${month}"
          version="${year}.${month}.${count}"
          sed -i "s/^version = \"0.0.0\"/version = \"$version\"/" Cargo.toml
          sed -i "s/^version = \"0.0.0\"/version = \"$version\"/" Cargo.lock
          git stage -- Cargo.toml Cargo.lock
          git commit -m"Release $version"

      - name: Validate release
        run: cargo package

      - name: Publish crate
        run: cargo publish --token ${CRATES_TOKEN}
        env:
          CRATES_TOKEN: ${{ secrets.CRATES_TOKEN }}
