name: Release

on:
  push:
    tags:
      - "[0-9]+.[0-9]+.[0-9]+"

permissions:
  contents: write

jobs:
  build-and-upload:
    name: Build and upload
    runs-on: ${{ matrix.os }}

    strategy:
      matrix:
        include:
          - build: linux
            os: ubuntu-latest
            skip_tests: false
            target: x86_64-unknown-linux-gnu

          - build: macos
            os: macos-latest
            skip_tests: false
            target: x86_64-apple-darwin

          - build: aarch64-macos
            os: macos-latest
            skip_tests: false
            target: aarch64-apple-darwin

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

      - name: Get the release version from the tag
        shell: bash
        run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV

      - uses: moonrepo/setup-rust@v1
        with:
          targets: ${{ matrix.target }}
      - name: Run cargo test
        if: "!matrix.skip_tests"
        run: cargo test --release --locked --target ${{ matrix.target }}
      - name: Build
        run: cargo build --verbose --release --locked --target ${{ matrix.target }}

      - name: Build archive
        shell: bash
        run: |
          binary_name="pik"

          dirname="$binary_name-${{ env.VERSION }}-${{ matrix.target }}"
          mkdir "$dirname"
          if [ "${{ matrix.os }}" = "windows-latest" ]; then
            mv "target/${{ matrix.target }}/release/$binary_name.exe" "$dirname"
          else
            mv "target/${{ matrix.target }}/release/$binary_name" "$dirname"
          fi

          if [ "${{ matrix.os }}" = "windows-latest" ]; then
            7z a "$dirname.zip" "$dirname"
            echo "ASSET=$dirname.zip" >> $GITHUB_ENV
          else
            tar -czf "$dirname.tar.gz" "$dirname"
            echo "ASSET=$dirname.tar.gz" >> $GITHUB_ENV
          fi

      - name: Release
        uses: softprops/action-gh-release@v2
        with:
          files: |
            ${{ env.ASSET }}

  publish-to-crates-io:
    name: Publish
    runs-on: ubuntu-latest
    needs: ['build-and-upload']
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
      - name: Setup rust
        uses: moonrepo/setup-rust@v1
      - name: Publish to crates.io
        run: cargo publish --token ${CRATES_TOKEN}
        env:
          CRATES_TOKEN: ${{ secrets.CRATES_TOKEN }}
