name: Release

on:
  push:
    branches: [main]

permissions:
  contents: write
  pull-requests: write

env:
  CARGO_TERM_COLOR: always

jobs:
  release-please:
    runs-on: ubuntu-latest
    outputs:
      release_created: ${{ steps.release.outputs.release_created }}
      tag_name: ${{ steps.release.outputs.tag_name }}
    steps:
      - uses: googleapis/release-please-action@v5
        id: release
        with:
          release-type: rust

  build:
    needs: release-please
    if: ${{ needs.release-please.outputs.release_created }}
    strategy:
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
            name: kmlcli-linux-x86_64
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
            name: kmlcli-linux-aarch64
          - target: x86_64-apple-darwin
            os: macos-latest
            name: kmlcli-macos-x86_64
          - target: aarch64-apple-darwin
            os: macos-latest
            name: kmlcli-macos-aarch64
          - target: x86_64-pc-windows-msvc
            os: windows-latest
            name: kmlcli-windows-x86_64.exe

    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install cross-compilation tools
        if: matrix.target == 'aarch64-unknown-linux-gnu'
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-aarch64-linux-gnu
          echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> $GITHUB_ENV

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

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

      - name: Rename binary
        shell: bash
        run: |
          if [[ "${{ matrix.os }}" == "windows-latest" ]]; then
            cp target/${{ matrix.target }}/release/kmlcli.exe ${{ matrix.name }}
          else
            cp target/${{ matrix.target }}/release/kmlcli ${{ matrix.name }}
          fi

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

  upload-assets:
    needs: [release-please, build]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v8
        with:
          path: artifacts
          merge-multiple: true

      - name: Upload release assets
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          gh release upload ${{ needs.release-please.outputs.tag_name }} artifacts/* \
            --repo ${{ github.repository }}

  publish-crate:
    needs: release-please
    if: ${{ needs.release-please.outputs.release_created }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@stable
      - run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
