name: Workflow to build and push docker image to registry
on:
  workflow_call:
    inputs:
      APP_NAME:
        required: true
        type: string
        description: Application name which would be the name of Docker and Helm release
      REGISTRY:
        required: true
        type: string
      DOCKERFILE_PATH:
        type: string
        default: Dockerfile
      USER_FOR_IMAGE_STORE:
        type: string
        default: registry-bot 
    secrets:
      VAULT_TOKEN:
        required: true

jobs:

  build:
    runs-on: ubuntu-latest
    container: 
      image: catthehacker/ubuntu:act-22.04

    steps:

      - name: Import Secrets
        uses: hashicorp/vault-action@v2
        with:
          url: https://vault.project-quest-dev.com
          token: ${{ secrets.VAULT_TOKEN }}
          secrets: |
            cicd/data/docker password | REGISTRY_PASSWORD ;
            cicd/data/docker username | REGISTRY_USERNAME ;
            cicd/data/submodule token | GIT_TOKEN         ;

      - name: Checkout code
        uses: actions/checkout@v4
        with:
          submodules: recursive
          fetch-depth: 0
          token: ${{ env.GIT_TOKEN }}

      - name: Set up Docker BuildX
        uses: docker/setup-buildx-action@v2
        with:
          driver-opts: network=host
          config-inline: |
             [registries.insecure]
              "${{ inputs.REGISTRY }}" = true                               

      - &get_version
        name: Extract version from tag or set commit SHA
        id: vars
        run: |
          if [ "${{ github.ref_type }}" = "tag" ]; then
            echo "VERSION=${{ github.ref_name }}" >> $GITHUB_ENV
          else
            VERSION=$(echo "${{ github.sha }}" | cut -c1-7)
            echo "VERSION=$VERSION" >> $GITHUB_ENV
          fi

      - name: Login to Docker registry
        uses: docker/login-action@v2
        with:
          registry: ${{ inputs.REGISTRY }}
          username: ${{ env.REGISTRY_USERNAME }}
          password: ${{ env.REGISTRY_PASSWORD }}

      - name: Build Docker image
        run: |
          docker build -t ${{ inputs.REGISTRY }}/${{ inputs.USER_FOR_IMAGE_STORE }}/${{ inputs.APP_NAME }}:${{ env.VERSION }} .          

      - name: Push Docker image
        run: |
          docker push ${{ inputs.REGISTRY }}/${{ inputs.USER_FOR_IMAGE_STORE }}/${{ inputs.APP_NAME }}:${{ env.VERSION }}          

      - name: Logout from Docker registry
        run: docker logout ${{ inputs.REGISTRY }}