#!/usr/bin/env bash

function resolve_resources(){
  local dir=$1
  local resolved_file_name=$2
  local image_prefix=$3
  local image_tag=$4

  [[ -n $image_tag ]] && image_tag=":$image_tag"

  echo "Writing resolved yaml to $resolved_file_name"

  > $resolved_file_name

  for yaml in "$dir"/*.yaml; do
    echo "---" >> $resolved_file_name
    # 1. Prefix test image references with test-
    # 2. Rewrite image references
    # 3. Remove comment lines
    # 4. Remove empty lines
    sed -e "s+\(.* image: \)\(knative.dev\)\(.*/\)\(test/\)\(.*\)+\1\2 \3\4test-\5+g" \
        -e "s+ko://++" \
        -e "s+knative-sources+knative-eventing+" \
        -e "s+contrib.eventing.knative.dev/release: devel+contrib.eventing.knative.dev/release: ${release}+" \
        -e "s+knative.dev/eventing-kafka/cmd/source/receive_adapter+${image_prefix}receive-adapter${image_tag}+" \
        -e "s+knative.dev/eventing-kafka/cmd/source/controller+${image_prefix}source-controller${image_tag}+" \
        -e "s+knative.dev/eventing-kafka/cmd/channel/consolidated/controller+${image_prefix}consolidated-controller${image_tag}+" \
        -e "s+knative.dev/eventing-kafka/cmd/channel/consolidated/dispatcher+${image_prefix}consolidated-dispatcher${image_tag}+" \
        -e "s+knative.dev/eventing-kafka/cmd/webhook+${image_prefix}webhook${image_tag}+" \
        -e "s+knative.dev/eventing-kafka/cmd/channel/distributed/controller+${image_prefix}distributed-controller${image_tag}+" \
        -e "s+knative.dev/eventing-kafka/cmd/channel/distributed/receiver+${image_prefix}receiver${image_tag}+" \
        -e "s+knative.dev/eventing-kafka/cmd/channel/distributed/dispatcher+${image_prefix}distributed-dispatcher${image_tag}+" \
        -e "s+\(.* image: \)\(knative.dev\)\(.*/\)\(.*\)+\1${image_prefix}\4${image_tag}+g" \
        -e '/^[ \t]*#/d' \
        -e '/^[ \t]*$/d' \
        "$yaml" >> $resolved_file_name
  done
}
