name: "Build deployment images"

on:
  workflow_call:
    inputs:
      target:
        required: true
        type: "string"
      registry:
        required: false
        type: "string"
        default: "docker-hosted.nexus.bthlabs.pl"
      platform:
        required: false
        type: "string"
        default: "linux/amd64,linux/arm64"
    secrets:
      VAULT_ROLE_ID:
        required: true
      VAULT_SECRET_ID:
        required: true

jobs:
  build-deployment-images:
    name: "Build deployment images"
    runs-on: "ubuntu-latest"
    steps:
      - name: "Checkout the code"
        uses: "actions/checkout@v2"
      - name: "Get build options"
        id: "get-build-options"
        uses: "./.gitea/actions/get-build-options"
      - name: "Get `backend` version"
        id: "get-backend-version"
        uses: "./.gitea/actions/get-service-version"
        with:
          service: "backend"
      - name: "Import Secrets"
        id: "import-secrets"
        uses: "hashicorp/vault-action@v2"
        with:
          url: "https://vault.bthlabs.pl/"
          method: "approle"
          roleId: "${{ secrets.VAULT_ROLE_ID }}"
          secretId: "${{ secrets.VAULT_SECRET_ID }}"
          secrets: |
            gitea/data/${{ inputs.registry }} username | DOCKER_USERNAME ;
            gitea/data/${{ inputs.registry }} password | DOCKER_PASSWORD
      - name: "Set up Docker Buildx"
        id: "setup-docker-buildx"
        uses: "docker/setup-buildx-action@v3"
        with:
          driver: "remote"
          endpoint: "tcp://builder-01.bthlab:2375"
          platforms: "linux/amd64"
          append: |
            - endpoint: "tcp://builder-mac-01.bthlab:2375"
              platforms: "linux/arm64"
      - name: "Login to Docker Registry"
        uses: "docker/login-action@v3"
        with:
          registry: "${{ inputs.registry }}"
          username: "${{ steps.import-secrets.outputs.DOCKER_USERNAME }}"
          password: "${{ steps.import-secrets.outputs.DOCKER_PASSWORD }}"
      - name: "Build `backend-aio` image"
        env:
          SHORT_SHA: "${{ steps.get-build-options.outputs.short-sha }}"
          VERSION: "${{ steps.get-backend-version.outputs.version }}"
          BUILD: "${{ steps.get-backend-version.outputs.build-number }}"
        run: |
          set -x
          docker buildx build \
            --cache-from "type=registry,ref=nexus.bthlab.bthlabs.net:8001/hotpocket" \
            --cache-to "type=registry,ref=nexus.bthlab.bthlabs.net:8001/hotpocket,target=max" \
            --push \
            --platform "${{ inputs.platform }}" \
            --build-arg IMAGE_ID="${{ inputs.target }}.${SHORT_SHA}" \
            -f services/backend/Dockerfile \
            --target "${{ inputs.target }}" \
            -t "${{ inputs.registry }}/hotpocket/backend:${{ inputs.target }}-${VERSION}-${BUILD}" \
            services/
