name: Release

on:
  push:
    tags:
      - 'v*'

env:
  CARGO_TERM_COLOR: always

jobs:
  build-release:
    name: Build Release
    runs-on: ${{ matrix.os }}
    permissions:
      contents: write
    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            artifact_name: lgit
            asset_name: lgit-linux-x86_64
          - os: macos-latest
            target: x86_64-apple-darwin
            artifact_name: lgit
            asset_name: lgit-macos-x86_64
          - os: macos-latest
            target: aarch64-apple-darwin
            artifact_name: lgit
            asset_name: lgit-macos-arm64
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            artifact_name: lgit.exe
            asset_name: lgit-windows-x86_64.exe
    steps:
      - uses: actions/checkout@v6

      - name: Install Rust
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: nightly-2026-06-04
          targets: ${{ matrix.target }}

      - name: Cache Rust dependencies
        uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

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

      - name: Strip binary
        if: matrix.os != 'windows-latest'
        run: strip target/${{ matrix.target }}/release/${{ matrix.artifact_name }}

      - name: Prepare release binary
        shell: bash
        run: cp target/${{ matrix.target }}/release/${{ matrix.artifact_name }} ${{ matrix.asset_name }}

      - name: Upload Release Asset
        uses: softprops/action-gh-release@v2
        with:
          files: ${{ matrix.asset_name }}

  publish-crate:
    name: Publish to crates.io
    needs: build-release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - name: Install Rust
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: nightly-2026-06-04

      - name: Verify crate packaging
        run: cargo package --allow-dirty

      - name: Publish
        run: |
          output=$(cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }} 2>&1) || {
            if echo "$output" | grep -qE "already (uploaded|exists)"; then
              echo "Version already published, skipping"
              exit 0
            else
              echo "$output"
              exit 1
            fi
          }
          echo "$output"
