#! /busybox/sh
# Idea comes from https://gitlab.com/Orange-OpenSource/gitlab-buildpkg
set -o nounset -o pipefail -o errexit

## All variables not defined and used later comes from environment
# CI_PROJECT_DIR must be equal to root of PF source tree (full path)

setup_vars() {
    # all specific variables need to be defined in kaniko_vars
    if [ -f "$CI_PROJECT_DIR/containers/kaniko_vars" ]; then
	source $CI_PROJECT_DIR/containers/kaniko_vars
    else
	echo "No specific variables added to build"
    fi

    # necessary if variables are not defined in kaniko_vars or in environment
    CI_COMMIT_TAG=${CI_COMMIT_TAG:-}
    DOCKFILE_PATH=${DOCKFILE_PATH:-"$CI_PROJECT_DIR/containers/$IMAGE_NAME/Dockerfile"}
    DOCKFILE_VARS=${DOCKFILE_VARS:-}
    KNK_CACHE=${KNK_CACHE:-true}

    # IMAGE_TAG is used inside DockerFile to reference other image
    # only one tag can be used in Dockerfile
    export IMAGE_TAG=$(echo $IMAGE_TAGS | cut -d ',' -f 1)

    echo "Building ${IMAGE_NAME} using ${DOCKFILE_PATH}"
}

generate_knk_config() {
    echo "{\"auths\":{\"$KNK_REGISTRY\":{\"username\":\"$KNK_REGISTRY_USER\",\"password\":\"$KNK_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
}

# we don't pass value of variables as build args, only their names
# values will be taken from environment
# so all DOCKFILE_VARS need to be exported if they are not
# already in the environment
generate_build_args() {
    local build_args=''
    if [ -n "${DOCKFILE_VARS}" ]; then
        for var in ${DOCKFILE_VARS}; do
          # just to handle case of first iteration
          if [ -z "$build_args" ]; then
            build_args="--build-arg ${var}"
          else
            build_args="$build_args --build-arg ${var}"
          fi
        done
        echo "$build_args"
    fi
}

detect_multi_tags() {
    # hack to get number of commas, zero comma means there is only one tag
    multi_tags=$(echo $IMAGE_TAGS|grep -o ','|wc -l)
}

sanitize_tag() {
    local tag=$1
    echo $tag | tr A-Z a-z | tr -c a-z0-9\\n -
}


# support multi-tags
# https://github.com/GoogleContainerTools/kaniko/issues/217
generate_destinations() {
    local destinations=''
    if detect_multi_tags; then
    # Multi-tags detected, parsing ${IMAGE_TAGS}"
    TAGS=$(echo $IMAGE_TAGS | tr ',' ' ')
    for tag in ${TAGS}; do
      tag_slug=$(sanitize_tag $tag)
      # just to handle case of first iteration
      if [ -z "$destinations" ]; then 
        destinations="--destination ${KNK_REGISTRY_URL}/${IMAGE_NAME}:${tag_slug}"
      else
        destinations="$destinations --destination ${KNK_REGISTRY_URL}/${IMAGE_NAME}:${tag_slug}"
      fi
    done
    else
      # only sanitize tag if we are not in a release process
      if [ -z "$CI_COMMIT_TAG" ]; then
          # Only one tag detected, using ${IMAGE_TAG} as tag
          tag_slug=$(sanitize_tag ${IMAGE_TAG})
      else
          tag_slug=${IMAGE_TAG}
      fi
      IMAGE_DEST="${KNK_REGISTRY_URL}/${IMAGE_NAME}:${tag_slug}"
      destinations="--destination ${IMAGE_DEST}"
    fi
    echo "$destinations"
}

generate_cache_opt() {
    local cache=''
    if [ "$KNK_CACHE" = true ]; then
        cache="--cache=true"
    else
        cache="--cache=false"
    fi
    echo "$cache"
}

build_image() {
    /kaniko/executor --context $CI_PROJECT_DIR \
         --dockerfile ${DOCKFILE_PATH} \
         $(generate_cache_opt) \
         $(generate_destinations) \
         $(generate_build_args)
}

setup_vars
generate_knk_config
# just to display options in CI jobs
generate_cache_opt
generate_destinations
generate_build_args
#
build_image
