#!/bin/sh

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

usage () {
    cat 1>&2 <<EOF
Wrapper for "docker build" with various enhancements.

Usage:

  $ $(basename $0) -t TAG [ARGS ...] CONTEXT

ARGS are passed unchanged to "docker build" after the workaround arguments.
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 \
                  "$@"
