#!/bin/bash
set -euo pipefail

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"

REPO_ROOT_PATH=$SCRIPTPATH/../
MAKE_FILE_PATH=$REPO_ROOT_PATH/Makefile

VERSION=$(make -s -f $MAKE_FILE_PATH version)
PLATFORMS=("linux/amd64")
GOPROXY="direct|https://proxy.golang.org"


USAGE=$(cat << 'EOM'
  Usage: build-docker-images  [-p <platform pairs>]
  Builds docker images for the platform pair

  Example: build-docker-images -p "linux/amd64,linux/arm"
          Optional:
            -p          Platform pair list (os/architecture) [DEFAULT: linux/amd64]
            -r          IMAGE REPO: set the docker image repo
            -v          VERSION: The application version of the docker image [DEFAULT: output of `make version`]
EOM
)

# Process our input arguments
while getopts "dp:r:v:" opt; do
  case ${opt} in
    p ) # Platform Pairs
        IFS=',' read -ra PLATFORMS <<< "$OPTARG"
      ;;
    r ) # Image Repo
        IMAGE_REPO="$OPTARG"
      ;;
    v ) # Image Version
        VERSION="$OPTARG"
      ;;
    \? )
        echo "$USAGE" 1>&2
        exit
      ;;
  esac
done

for os_arch in "${PLATFORMS[@]}"; do
    os=$(echo $os_arch | cut -d'/' -f1)
    arch=$(echo $os_arch | cut -d'/' -f2)

    img_tag="$IMAGE_REPO:$VERSION-$os-$arch"

    docker build \
        --build-arg GOOS=${os} \
        --build-arg GOARCH=${arch} \
        --build-arg GOPROXY=${GOPROXY} \
        -t ${img_tag} \
        ${REPO_ROOT_PATH}
done