name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

jobs:
  build-linux:
    name: Build ${{ matrix.target }}
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        target:
          - x86_64-unknown-linux-gnu
          - aarch64-unknown-linux-gnu

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

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install cross
        run: cargo install cross --git https://github.com/cross-rs/cross

      - name: Build
        run: cross build --release --target ${{ matrix.target }}

      - name: Package
        run: |
          cd target/${{ matrix.target }}/release
          tar czvf ../../../pgmold-${{ matrix.target }}.tar.gz pgmold

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: pgmold-${{ matrix.target }}
          path: pgmold-${{ matrix.target }}.tar.gz

  build-macos:
    name: Build ${{ matrix.target }}
    runs-on: macos-latest
    strategy:
      fail-fast: false
      matrix:
        target:
          - x86_64-apple-darwin
          - aarch64-apple-darwin

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

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Build
        run: cargo build --release --target ${{ matrix.target }}

      - name: Package
        run: |
          cd target/${{ matrix.target }}/release
          tar czvf ../../../pgmold-${{ matrix.target }}.tar.gz pgmold

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: pgmold-${{ matrix.target }}
          path: pgmold-${{ matrix.target }}.tar.gz

  release:
    name: Create Release
    needs: [build-linux, build-macos]
    runs-on: ubuntu-latest
    steps:
      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts
          merge-multiple: true

      - name: Create checksums
        run: |
          cd artifacts
          sha256sum *.tar.gz > checksums-sha256.txt

      - name: Upload to release
        uses: softprops/action-gh-release@v2
        with:
          files: |
            artifacts/*.tar.gz
            artifacts/checksums-sha256.txt
