# SPDX-FileCopyrightText: 2024-2025 Sarah Vaupel <sarah.vaupel@uniworx.de>
#
# SPDX-License-Identifier: AGPL-3.0-or-later

parameters:
  - name: imageName
    type: string
  - name: imageBase
    type: object

jobs:
- job: SetupImage_${{parameters.imageName}}
  displayName: Build ${{parameters.imageName}} image
  condition: eq(variables.setupImages, true)
  container:
    image: devfra.azurecr.io/de.fraport.build/tools:1.1.0
    endpoint: devfra
  steps:
    - task: Docker@2
      displayName: Login to container registry
      inputs:
        command: login
        containerRegistry: devfra
    - task: Bash@3
      displayName: Build ${{parameters.imageName}} image
      inputs:
        targetType: inline
        script: |
          cp docker/${{parameters.imageName}}/Dockerfile .
          docker build \
          --tag $(buildImageUpstream)/${{parameters.imageName}}:$(Build.BuildNumber) \
          --build-arg FROM_IMG=${{parameters.imageBase.image}} \
          --build-arg FROM_TAG=${{parameters.imageBase.tag}} \
          --build-arg HTTPS_PROXY=http://proxy.frankfurt-airport.de:8080 \
          --build-arg HTTP_PROXY=http://proxy.frankfurt-airport.de:8080 \
          --build-arg NO_PROXY='localhost,127.0.0.1,*.docker.internal,*.azmk8s.io,devfra.azurecr.io,devfra.westeurope.data.azurecr.io' \
          --build-arg FRAPORT_NOPROXY=dev.azure.com,*.dev.azure.com,*.fraport.de,*.frankfurt-airport.de \
          --build-arg PROJECT_DIR=$(Build.Repository.LocalPath) \
          --build-arg IN_CI=true \
          --build-arg IN_CONTAINER=true \
          .
    - task: Bash@3
      displayName: Push ${{parameters.imageName}} image
      inputs:
        targetType: inline
        script: |
          docker push $(buildImageUpstream)/${{parameters.imageName}}:$(Build.BuildNumber)
    - task: Bash@3
      displayName: Update latest ${{parameters.imageName}} image
      condition: or(eq(variables.forcePushLatest, true), eq(variables['Build.SourceBranch'], 'refs/heads/master'))
      inputs:
        targetType: inline
        script: |
          docker tag $(buildImageUpstream)/${{parameters.imageName}}:$(Build.BuildNumber) $(buildImageUpstream)/${{parameters.imageName}}:latest
          docker push $(buildImageUpstream)/${{parameters.imageName}}:latest
    - task: Bash@3
      displayName: Save image for publication
      inputs:
        targetType: inline
        script: |
          docker image save --output=$(Build.ArtifactStagingDirectory)/${{parameters.imageName}}.tar $(buildImageUpstream)/${{parameters.imageName}}:$(Build.BuildNumber)
    - task: PublishBuildArtifacts@1
      displayName: Publish image as artifact
      inputs:
        PathtoPublish: '$(Build.ArtifactStagingDirectory)'
        ArtifactName: Image_${{parameters.imageName}}
        publishLocation: 'Container'
    - task: Docker@2
      displayName: Logout from container registry
      inputs:
        command: logout
        containerRegistry: devfra