# Build iios-service and deploy it via k8s-pods (ArgoCD). Runs on the dind-builder
# host-mode runner (mounts the host docker socket). On every push to main that
# touches the service, it builds+pushes the image (SHA-tagged) and bumps the tag in
# platform-engineering/k8s-pods -> ArgoCD rolls it.
name: Deploy iios-service

on:
  push:
    branches: [main]
    paths:
      - "packages/iios-service/**"
      - "packages/iios-adapter-sdk/**"
      - "packages/iios-contracts/**"
      - "pnpm-lock.yaml"
      - ".github/workflows/deploy-iios-service.yml"

jobs:
  build-deploy:
    runs-on: dind-builder
    steps:
      - uses: actions/checkout@v4

      - name: Log in to the Gitea container registry
        run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.lynkedup.cloud -u mcp-bot --password-stdin

      - name: Ensure docker buildx (the Dockerfile uses BuildKit --mount)
        run: |
          if ! docker buildx version >/dev/null 2>&1; then
            mkdir -p ~/.docker/cli-plugins
            curl -sSL https://github.com/docker/buildx/releases/download/v0.19.3/buildx-v0.19.3.linux-amd64 -o ~/.docker/cli-plugins/docker-buildx
            chmod +x ~/.docker/cli-plugins/docker-buildx
          fi
          docker buildx create --use --name iios-ci 2>/dev/null || docker buildx use iios-ci

      - name: Build and push image
        run: |
          IMG=git.lynkedup.cloud/platform-engineering/iios-service
          TAG=$(git rev-parse --short HEAD)
          echo "TAG=$TAG" >> "$GITHUB_ENV"
          docker buildx build --builder iios-ci --push \
            -t "$IMG:$TAG" -f packages/iios-service/Dockerfile .

      - name: Bump k8s-pods image tag (ArgoCD deploys)
        run: |
          git clone --depth 1 -b main \
            "https://mcp-bot:${{ secrets.K8S_PODS_TOKEN }}@git.lynkedup.cloud/platform-engineering/k8s-pods.git" /tmp/kp
          cd /tmp/kp
          sed -i "s#image: git.lynkedup.cloud/platform-engineering/iios-service:.*#image: git.lynkedup.cloud/platform-engineering/iios-service:${TAG}#" services/iios/deployment.yaml
          git config user.name "iios-ci"; git config user.email "ci@lynkedup.cloud"
          if git diff --quiet; then echo "image tag unchanged"; exit 0; fi
          git commit -am "ci(iios): deploy iios-service ${TAG}"
          git push origin main
