name: Release

on:
  push:
    tags:
      - 'v*'

env:
  CARGO_TERM_COLOR: always

jobs:
  # Create GitHub release
  create-release:
    name: Create Release
    runs-on: ubuntu-latest
    outputs:
      upload_url: ${{ steps.create_release.outputs.upload_url }}
    steps:
      - uses: actions/checkout@v4
      - name: Create Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ github.ref }}
          release_name: Release ${{ github.ref }}
          draft: false
          prerelease: false

  # Build and upload binaries
  build-binaries:
    name: Build Binaries
    needs: create-release
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            suffix: linux-amd64
          - os: macos-latest
            target: x86_64-apple-darwin
            suffix: darwin-amd64
          - os: macos-latest
            target: aarch64-apple-darwin
            suffix: darwin-arm64
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            suffix: windows-amd64.exe
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}
      - name: Build release binary
        run: cargo build --release --target ${{ matrix.target }} --package ruchy-cli
      - name: Package binary
        shell: bash
        run: |
          if [[ "${{ matrix.os }}" == "windows-latest" ]]; then
            cp target/${{ matrix.target }}/release/ruchy.exe ruchy-${{ matrix.suffix }}
          else
            cp target/${{ matrix.target }}/release/ruchy ruchy-${{ matrix.suffix }}
          fi
      - name: Upload Release Asset
        uses: actions/upload-release-asset@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          upload_url: ${{ needs.create-release.outputs.upload_url }}
          asset_path: ./ruchy-${{ matrix.suffix }}
          asset_name: ruchy-${{ matrix.suffix }}
          asset_content_type: application/octet-stream

  # Publish to crates.io
  publish-crates:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    needs: create-release
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - name: Publish ruchy library
        run: cargo publish --package ruchy --token ${{ secrets.CRATES_TOKEN }}
        continue-on-error: true
      - name: Wait for library to be available
        run: sleep 30
      - name: Publish ruchy-cli
        run: cargo publish --package ruchy-cli --token ${{ secrets.CRATES_TOKEN }}
        continue-on-error: true