name: Build demo-service

on:
  push:
    branches: [master]
    paths:
      - 'home-apps/demo-service/**'
  workflow_dispatch:

permissions:
  contents: write
  packages: write

jobs:
  build:
    name: Build & update manifest
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

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

      - name: Log in to ghcr.io
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Compute image tag
        id: tag
        run: |
          SHA="${{ github.sha }}"
          SHORT_SHA="${SHA:0:7}"
          TAG="git-${SHORT_SHA}"
          echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
          echo "full_image=ghcr.io/${{ github.repository_owner }}/demo-manager:${TAG}" >> "$GITHUB_OUTPUT"

      - name: Build & push image
        uses: docker/build-push-action@v5
        with:
          context: home-apps/demo-service
          file: home-apps/demo-service/Dockerfile
          push: true
          tags: |
            ghcr.io/${{ github.repository_owner }}/demo-manager:${{ steps.tag.outputs.tag }}
            ghcr.io/${{ github.repository_owner }}/demo-manager:latest
          labels: |
            org.opencontainers.image.revision=${{ github.sha }}
            org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}

      - name: Update manifest with new image tag
        run: |
          IMAGE="${{ steps.tag.outputs.full_image }}"
          echo "Updating manifest to: ${IMAGE}"
          # Match any demo-manager image reference (works for any current value)
          sed -i "s|image: docker.io/library/demo-manager:.*|image: ${IMAGE}|" home-apps/demo-service.yaml
          sed -i "s|image: ghcr.io/wahyd4/demo-manager:.*|image: ${IMAGE}|" home-apps/demo-service.yaml
          sed -i "s|imagePullPolicy:.*|imagePullPolicy: Always|" home-apps/demo-service.yaml
          # Show what changed
          git diff home-apps/demo-service.yaml || echo "No diff produced"

      - name: Commit & push manifest update
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add home-apps/demo-service.yaml
          if git diff --cached --quiet; then
            echo "No manifest changes to commit"
            exit 0
          fi
          git commit -m "ci(demo-service): bump image to ${{ steps.tag.outputs.tag }}"
          git push
