name: Publish

on:
  push:
    tags: ['v[0-9]+.[0-9]+.[0-9]+']

permissions:
  contents: write

jobs:
  verify:
    name: Verify package
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - name: Install libx11-dev
        run: sudo apt-get update && sudo apt-get install -y libx11-dev
      - run: cargo fmt --all -- --check
      - run: cargo clippy -- -D warnings
      - run: cargo package --no-verify

  publish-crates:
    name: Publish to crates.io
    needs: verify
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - name: Install libx11-dev
        run: sudo apt-get update && sudo apt-get install -y libx11-dev
      - name: Verify tag matches version
        run: |
          VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
          TAG=${GITHUB_REF#refs/tags/v}
          if [ "$VERSION" != "$TAG" ]; then
            echo "Version mismatch: Cargo.toml=$VERSION tag=$TAG"
            exit 1
          fi
      - run: cargo publish --token ${{ secrets.CRATES_TOKEN }}

  github-release:
    name: Create GitHub Release
    needs: publish-crates
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            ext: .exe
            archive: showpid-windows-x86_64.zip
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            ext: ""
            archive: showpid-linux-x86_64.tar.gz
          - os: macos-latest
            target: x86_64-apple-darwin
            ext: ""
            archive: showpid-macos-x86_64.tar.gz
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}
      - if: runner.os == 'Linux'
        run: sudo apt-get update && sudo apt-get install -y libx11-dev
      - run: cargo build --release --target ${{ matrix.target }}
      - name: Package artifact
        shell: bash
        run: |
          mkdir -p release
          cp target/${{ matrix.target }}/release/showpid${{ matrix.ext }} release/
          cp README.md LICENSE release/
          if [[ "${{ matrix.archive }}" == *.zip ]]; then
            7z a ${{ matrix.archive }} ./release/*
          else
            tar czf ${{ matrix.archive }} -C release .
          fi
      - name: Upload to release
        uses: softprops/action-gh-release@v2
        with:
          files: ${{ matrix.archive }}