name: Nightly 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 Docker image tag
        id: tag
        run: |
          if [ "${GITHUB_REF_NAME}" == "main" ]; then
            TAG="nightly"
          else
            TAG="${GITHUB_REF_NAME}-nightly"
          fi
          echo "Using 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: 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 }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

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

      - uses: pyTooling/Actions/releaser@r0
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          tag: ${{ needs.get-tag.outputs.tag }}
          rm: true
          files: binaries/*
