name: release

on:
  workflow_dispatch:
    inputs:
      version:
        description: The version to release, without the leading `v`.
        type: string
        required: true

env:
  bot-name: nekit[bot]
  bot-email: bot@nekit.dev
  changelog: CHANGELOG-${{ inputs.version }}.md

jobs:
  changelog:
    runs-on: ubuntu-latest

    permissions:
      contents: write

    steps:
      - name: Checkout
        uses: actions/checkout@v7

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

      - name: Install changelogging
        run: cargo install changelogging

      - name: Build changelog ${{ inputs.version }}
        run: changelogging preview > ${{ env.changelog }}

      - name: Upload changelog ${{ inputs.version }}
        uses: actions/upload-artifact@v7
        with:
          name: changelog
          path: ${{ env.changelog }}

      - name: Build changelog
        run: changelogging build --stage --remove

      - name: Setup bot user
        run: |
          git config --local user.name ${{ env.bot-name }}
          git config --local user.email ${{ env.bot-email }}

      - name: Commit and push
        run: |
          git commit -m "Add ${{ inputs.version }} to the changelog."
          git push

  tag:
    runs-on: ubuntu-latest
    needs: changelog

    permissions:
      contents: write

    steps:
      - name: Checkout
        uses: actions/checkout@v7

      - name: Setup bot user
        run: |
          git config --local user.name ${{ env.bot-name }}
          git config --local user.email ${{ env.bot-email }}

      - name: Tag and push
        run: |
          git tag v${{ inputs.version }}
          git push --tags

  publish:
    runs-on: ubuntu-latest
    needs: tag

    steps:
      - name: Checkout
        uses: actions/checkout@v7

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

      - name: Publish
        run: cargo publish --workspace --token ${{ secrets.CARGO_TOKEN }}

  release:
    runs-on: ubuntu-latest
    needs: publish

    steps:
      - name: Download changelog
        uses: actions/download-artifact@v8
        with:
          pattern: changelog
          merge-multiple: true

      - name: Publish to GitHub
        uses: softprops/action-gh-release@v3
        with:
          body_path: ${{ env.changelog }}
          tag_name: v${{ inputs.version }}
          token: ${{ secrets.BOT_TOKEN }}
