name: Release

on:
  push:
    tags: ['v*']

permissions:
  contents: write

env:
  CARGO_TERM_COLOR: always

jobs:
  test:
    name: Test (${{ matrix.os }})
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v5
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - run: cargo test

  check-version:
    name: Check version consistency
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - name: Verify tag matches Cargo.toml version
        run: |
          tag="${GITHUB_REF_NAME#v}"
          cargo_version=$(grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)".*/\1/')
          if [ "$tag" != "$cargo_version" ]; then
            echo "::error::Tag v${tag} does not match Cargo.toml version ${cargo_version}"
            exit 1
          fi

  build:
    name: Build (${{ matrix.target }})
    needs: [test, check-version]
    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            archive: tar.gz
          - os: macos-latest
            target: aarch64-apple-darwin
            archive: tar.gz
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            archive: zip
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v5
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - run: cargo build --release

      - name: Package (Unix)
        if: matrix.archive == 'tar.gz'
        run: tar czf tgltrk-${{ matrix.target }}.tar.gz -C target/release tgltrk

      - name: Package (Windows)
        if: matrix.archive == 'zip'
        shell: pwsh
        run: Compress-Archive -Path target/release/tgltrk.exe -DestinationPath tgltrk-${{ matrix.target }}.zip

      - uses: actions/upload-artifact@v7
        with:
          name: tgltrk-${{ matrix.target }}
          path: tgltrk-${{ matrix.target }}.${{ matrix.archive }}

  release:
    name: Release
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5

      - uses: actions/download-artifact@v8
        with:
          path: artifacts
          merge-multiple: true

      - name: Create release
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          tag="${GITHUB_REF_NAME}"
          prerelease=""
          if echo "$tag" | grep -qE '(alpha|beta|rc)'; then
            prerelease="--prerelease"
          fi
          gh release create "$tag" $prerelease --generate-notes artifacts/*
