name: Release CI

on:
  workflow_dispatch:
  push:
    tags:
      - "v*"

env:
  CARGO_TERM_COLOR: always

jobs:
  ci:
    runs-on: macos-latest

    env:
      MACOSX_DEPLOYMENT_TARGET: 11
      FILE_NAME: cutler-aarch64-apple-darwin.tar.gz
      SCCACHE_GHA_ENABLED: "true"
      SCCACHE_CACHE_SIZE: 2G
      RUSTC_WRAPPER: "sccache"

    steps:
      - uses: actions/checkout@v6

      - uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: stable
          override: true

      - uses: Swatinem/rust-cache@v2
      - uses: mozilla-actions/sccache-action@v0.0.9

      - name: Build release artifact
        run: cargo build --release --quiet --locked

      - run: sccache --show-stats || true

      - name: Package release
        run: |
          mkdir -p release/bin release/man/man1
          cp target/aarch64-apple-darwin/release/cutler release/bin/
          cp man/man1/cutler.1 release/man/man1/
          cp LICENSE-APACHE release/
          cp LICENSE-MIT release/
          cp README.md release/
          tar -C release -czf $FILE_NAME bin man README.md LICENSE-APACHE LICENSE-MIT

      - name: Set release body
        id: release_body
        run: |
          body=$(cat RELEASE.md)
          echo "body<<EOF" >> $GITHUB_OUTPUT
          echo "$body" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Release
        uses: softprops/action-gh-release@v2
        with:
          body: ${{ steps.release_body.outputs.body }}
          files: ${{ env.FILE_NAME }}

      - name: Prepare Crates.io README
        run: sed -i '' '/^>/d' README.md

      - name: Publish to crates.io
        env:
          CRATES_TOKEN: ${{ secrets.CRATES_TOKEN }}
        run: cargo publish --token $CRATES_TOKEN --allow-dirty
