name: Build and Push Spoon Images

on:
  push:
    branches: [main]
    paths:
      - 'apps/**'
      - 'packages/**'
      - 'tools/**'
      - 'scripts/**'
      - 'docker/**'
      - '.gitea/workflows/build-next.yml'
      - '.infisical.json'
      - 'package.json'
      - 'bun.lock'
      - 'turbo.json'

jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: oven-sh/setup-bun@v2
        with:
          bun-version: 1.3.10
      - run: bun install --frozen-lockfile
      - name: Lint, typecheck, and test
        env:
          DOTENV_PROD: ${{ secrets.DOTENV_PROD }}
        run: |
          env_file="$(mktemp)"
          trap 'rm -f "$env_file"' EXIT
          printf '%s\n' "$DOTENV_PROD" > "$env_file"
          bunx dotenv -e "$env_file" -- env NODE_ENV=test SKIP_E2E=1 bun run ci:check

  build-images:
    needs: [quality]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Log in to container registry
        run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.gbrown.org -u "${{ secrets.REGISTRY_USER }}" --password-stdin
      - uses: oven-sh/setup-bun@v2
        with:
          bun-version: 1.3.10
      - run: bun install --frozen-lockfile
      - name: Build Next image
        env:
          DOTENV_PROD: ${{ secrets.DOTENV_PROD }}
        run: |
          env_file="$(mktemp)"
          trap 'rm -f "$env_file"' EXIT
          printf '%s\n' "$DOTENV_PROD" > "$env_file"
          CI_ENV_FILE="$env_file" ./scripts/build-next-app production
      - name: Build agent images
        env:
          SPOON_BUILD_SHA: ${{ gitea.sha }}
        run: SPOON_AGENT_CONTAINER_RUNTIME=docker ./scripts/build-agent-images
      - name: Tag and push images
        run: |
          docker tag spoon-next:latest git.gbrown.org/gib/spoon-next:${{ gitea.sha }}
          docker tag spoon-next:latest git.gbrown.org/gib/spoon-next:latest
          docker push git.gbrown.org/gib/spoon-next:${{ gitea.sha }}
          docker push git.gbrown.org/gib/spoon-next:latest

          docker tag spoon-agent-worker:latest git.gbrown.org/gib/spoon-agent-worker:${{ gitea.sha }}
          docker tag spoon-agent-worker:latest git.gbrown.org/gib/spoon-agent-worker:latest
          docker push git.gbrown.org/gib/spoon-agent-worker:${{ gitea.sha }}
          docker push git.gbrown.org/gib/spoon-agent-worker:latest

          docker tag spoon-agent-job:latest git.gbrown.org/gib/spoon-agent-job:${{ gitea.sha }}
          docker tag spoon-agent-job:latest git.gbrown.org/gib/spoon-agent-job:latest
          docker push git.gbrown.org/gib/spoon-agent-job:${{ gitea.sha }}
          docker push git.gbrown.org/gib/spoon-agent-job:latest
