#!/usr/bin/env bash
set -e
cd "$(dirname $(dirname "$0"))" || exit

. .env

build () {
  echo "build: $1"
  . "$1/.env"
  for PROJECT in "${DOCKER_PROJECTS[@]}"; do
    IFS=: read -r PROJECT_NAME PROJECT_TARGET <<< "$PROJECT"
    ARGS=("build")
    for ARG in ${DOCKER_ARGS[@]}; do
      ARGS+=("--build-arg" "$ARG")
    done
    if [ -n "$PROJECT_TARGET" ]; then
      ARGS+=("--target" "$PROJECT_TARGET")
    fi
    ARGS+=("-t" "$DOCKER_GROUP/$PROJECT_NAME" ".")
    ARGS+=("-f" "$1/Dockerfile")
    echo "${ARGS[@]}"
    docker "${ARGS[@]}"
  done
}

publish () {
  echo "publish: $1"
  . "$1/.env"
  for PROJECT in "${DOCKER_PROJECTS[@]}"; do
    IFS=: read -r PROJECT_NAME PROJECT_TARGET <<< "$PROJECT"
    docker tag $DOCKER_GROUP/$PROJECT_NAME $DOCKER_ROOT/$PROJECT_NAME:$VERSION
    docker tag $DOCKER_GROUP/$PROJECT_NAME $DOCKER_ROOT/$PROJECT_NAME:latest
    docker push $DOCKER_ROOT/$PROJECT_NAME:$VERSION
    docker push $DOCKER_ROOT/$PROJECT_NAME:latest
  done
}

DEFAULT_TARGETS="."
TARGETS="${@-$DEFAULT_TARGETS}"

DOCKER_ACTION="${DOCKER_ACTION-build}"

for TARGET in $TARGETS; do
  $DOCKER_ACTION "$TARGET"
done
