#!/bin/bash

LOCATION="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# default arguments
TAG_BASENAME=registry.gitlab.com/signalytic/client-external/streamline/streamline-emr

function print_usage {
  echo "Streamline EMR Docker Image Utils"
  echo
  echo "Usage: build-image [ OPTIONS ]"
  echo
  echo "Options:"
  echo "  -h                 Print this help prompt and exit"
  echo "  -p                 Push images to a remote registry"
  echo "  -f DOCKERFILE      Specify a docker file to build, may be passed multiple"
  echo "                     times. If none specified, all targets built"
  echo "  -b TAG_BASENAME    Images will be tagged with '<TAG_BASENAME>/<name>/<arch>:<version>'."
  echo "                     Default: '${TAG_BASENAME}'"
  echo "  -v VERSION         Set image tag. It not specified, version will be taken from git"
  echo
}

# collect user args
DOCKERFILES=()
while getopts ":f:b:v:ph" options; do
  case "${options}" in
    p)
      PUSH_IMAGES=1
      ;;
    f)
      DOCKERFILES+=(${OPTARG})
      ;;
    b)
      TAG_BASENAME=${OPTARG}
      ;;
    v)
      VERSION_NAME=${OPTARG}
      ;;
    h)
      print_usage
      exit 0
      ;;
    *)
      print_usage
      exit 1
      ;;
  esac
done
shift $((OPTIND -1))
set -e

# if not set, determine version name from git
if [ -z $VERSION_NAME ];then
  # use ci tag name if available (e.g. "v1.2")
  if [ $CI_COMMIT_TAG ]; then
    VERSION_NAME="$CI_COMMIT_TAG"
  # otherwise if ci, use BRANCH-COMMIT
  elif [ $CI_COMMIT_BRANCH ]; then
    VERSION_NAME="$CI_COMMIT_REF_SLUG-$CI_COMMIT_SHORT_SHA"
  # if not ci, try to use git
  elif command -v git &> /dev/null; then
    VERSION_NAME=$(git describe --always --tags --abbrev=7 --dirty)
  # fallback
  else
    VERSION_NAME="latest"
  fi
fi

# if not specified, process all docker files
if [ ${#DOCKERFILES[@]} -eq 0 ]; then
  DOCKERFILES=($(find ${LOCATION} -maxdepth 1 -name "Dockerfile.*"))
fi

# process dockerfiles one at a time
for f in ${DOCKERFILES[@]}; do
  echo
  echo "Processing file '$f'"

  # extract remaining info from filename
  filename=$(basename $f)
  basename=${filename%.*}
  name=${basename:11}
  arch=${filename##*.}
  platform="linux/${arch}"
  tag=${TAG_BASENAME}/${name}/${arch}:${VERSION_NAME}
  echo "  name: '${name}'"
  echo "  platform: '${platform}'"
  echo "  tag: '${tag}'"

  # build the image
  echo "docker build --platform ${platform} -f $f -t ${tag} ${LOCATION}"
  docker build --platform ${platform} -f $f -t ${tag} ${LOCATION}

  # push image if requested build was successful
  if [ $? -eq 0 ] && [ "${PUSH_IMAGES}" = "1" ];then
    echo "docker push ${tag}"
    docker push ${tag}

    latest_tag="${TAG_BASENAME}/${name}/${arch}:latest"
    docker tag ${tag} ${latest_tag}
    echo "docker push ${latest_tag}"
    docker push ${latest_tag}
  fi
done
