name: Release
on:
  workflow_dispatch:

jobs:
  get-tag:
    runs-on: ubuntu-latest
    outputs:
      tag: ${{ steps.tag.outputs.tag }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Get current tag
        id: tag
        run: |
          TAG=v$(head -n 4 Cargo.toml | grep version | awk '{print $3}' | tr -d '"')
          echo "Current tag: $TAG"
          echo "tag=$TAG" >> $GITHUB_OUTPUT

  build-binaries:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Rust
        uses: actions-rust-lang/setup-rust-toolchain@v1

      - name: Install cross
        run: RUSTFLAGS="" cargo install cross --git https://github.com/cross-rs/cross

      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Set up Bun
        uses: oven-sh/setup-bun@v1

      - name: Install deps
        run: cd web && bun install

      - name: Build amd64 binary
        run: |
          ./build.sh cross build --target x86_64-unknown-linux-musl --release
          mv target/x86_64-unknown-linux-musl/release/cup ./cup-linux-amd64

      - name: Build arm64 binary
        run: |
          ./build.sh cross build --target aarch64-unknown-linux-musl --release
          mv target/aarch64-unknown-linux-musl/release/cup ./cup-linux-arm64

      - name: Upload binaries
        uses: actions/upload-artifact@v4
        with:
          name: binaries
          path: |
            cup-linux-amd64
            cup-linux-arm64

  build-image:
    needs: get-tag
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push image
        uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64, linux/arm64
          push: true
          tags: ghcr.io/sergi0g/cup:${{ needs.get-tag.outputs.tag }},ghcr.io/sergi0g/cup:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max

  release:
    runs-on: ubuntu-latest
    needs: [get-tag, build-image, build-binaries]
    steps:
      - name: Download binaries
        uses: actions/download-artifact@v4
        with:
          name: binaries
          path: binaries

      - name: Create release
        uses: softprops/action-gh-release@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          prerelease: true
          tag_name: ${{ needs.get-tag.outputs.tag }}
          name: ${{ needs.get-tag.outputs.tag }}
          files: binaries/*