#!/bin/sh

LIBEXEC="$(cd "$(dirname "$0")" && pwd)"
. ${LIBEXEC}/base.sh

usage () {
    cat 1>&2 <<EOF
Wrapper for "docker build" that works around some of its annoying behaviors.

Usage:

  $ $(basename $0) [ARGS ...]

ARGS are passed unchanged to "docker build" after the workaround arguments.

Workarounds:

  * Add the HTTP proxy environment variables with "--build-arg".

  * Default to the Dockerfile in CWD with "--file", if one exists and --file
    wasn't already specified, rather than the one at the root of the build
    context. This works around Docker's hostility to symlinks (e.g., see
    https://github.com/docker/docker/issues/1676).

EOF
    exit ${1:-1}
}

if [ "$1" = "--help" ]; then
    usage 0
fi
if [ "$1" = "--version" ]; then
    version
    exit 0
fi

dockerfile=
if [ -f Dockerfile ]; then
    dockerfile="--file=$PWD/Dockerfile"
    for arg in "$@"; do
        if [ "${arg#--file}" != "$arg" ]; then
            # --file already specified, don't override
            dockerfile=
            break
        fi
    done
fi

# Coordinate this list with test "build.bats/proxy variables".
sudo docker build --build-arg HTTP_PROXY=$HTTP_PROXY \
                  --build-arg HTTPS_PROXY=$HTTPS_PROXY \
                  --build-arg NO_PROXY=$NO_PROXY \
                  --build-arg http_proxy=$http_proxy \
                  --build-arg https_proxy=$https_proxy \
                  --build-arg no_proxy=$no_proxy \
                  $dockerfile \
                  "$@"
