name: Release

on:
  push:
    tags:
      - mdcat-*

jobs:
  build-manpage:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: docker://asciidoctor/docker-asciidoctor
        with:
          args: asciidoctor -b manpage -a reproducible mdcat.1.adoc
      - uses: actions/upload-artifact@v4
        with:
          name: mdcat.1
          path: mdcat.1

  build-binaries:
    runs-on: "${{ matrix.os }}"
    needs: build-manpage
    permissions:
      id-token: write
      contents: read
      attestations: write
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest]
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - os: windows-latest
            target: x86_64-pc-windows-msvc
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}
      - uses: actions/download-artifact@v4
        with:
          path: ./artifacts
      - run: mv artifacts/mdcat.1 .
      - run: cargo build --locked --target '${{ matrix.target }}' --release
      - run: strip 'target/${{ matrix.target }}/release/mdcat'
        if: ${{ !contains(matrix.target, 'windows') }}
      - id: version
        shell: bash
        run: |
          echo "version=$(cargo pkgid | cut -d'#' -f2 | cut -d: -f2)" >>"${GITHUB_OUTPUT}"
      - id: package
        shell: bash
        run: ./scripts/package '${{ steps.version.outputs.version }}' '${{ matrix.target }}'
      - uses: actions/attest-build-provenance@v2
        with:
          subject-path: ${{ steps.package.outputs.file }}
      - uses: actions/upload-artifact@v4
        with:
          name: ${{ steps.package.outputs.name }}
          path: ${{ steps.package.outputs.file }}

  create-release:
    runs-on: ubuntu-latest
    needs: build-binaries
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
      - uses: actions/download-artifact@v4
        with:
          path: ./artifacts
      - run: mkdir ./assets
      - run: mv ./artifacts/*/*.{zip,tar.gz} ./assets
      - run: b2sum *.{zip,tar.gz} > B2SUMS.txt
        working-directory: assets
      - id: version
        shell: bash
        run: |
          echo "version=$(cargo pkgid | cut -d'#' -f2 | cut -d: -f2)" >>"${GITHUB_OUTPUT}"
      - name: Extract changelog
        shell: bash
        run: |
          awk -v r='${{ steps.version.outputs.version }}' \
            '/^\[[^]]*\]/{print $0}/^## \[[0-9]/ && match($0, /\[[0-9][^]]*\]/){if (r == substr($0, RSTART+1, RLENGTH-2)) { p=1; next } else { p=0 } }p' \
            CHANGELOG.md > ./CHANGELOG-release.md
          cat CHANGELOG-release.md
      - uses: softprops/action-gh-release@v2
        with:
          name: mdcat-${{ steps.version.outputs.version }}
          body_path: ./CHANGELOG-release.md
          files: "./assets/*"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
