#!/bin/bash

TEMPDIR="./tmp"
IMAGE_BASE=ubuntu

function die() {
    echo "$@" >&2
    exit 1
}

# Use the environment variables by default.
MPD_VERSION="${MPD_VERSION:-}"
LIBMPDCLIENT_VERSION="${LIBMPDCLIENT_VERSION:-}"
IMAGE_TAG="${IMAGE_TAG:-test/mpd:latest}"

declare -a DOCKER_ARGS
while test "$#" -gt 0; do
    case "$1" in
        -m|--mpd-version)
            MPD_VERSION="$2"
            shift 2
            ;;
        -l|--libmpdclient-version)
            LIBMPDCLIENT_VERSION="$2"
            shift 2
            ;;
        -t|--image-tag)
            IMAGE_TAG="$2"
            shift 2
            ;;
        *)
            DOCKER_ARGS+=( "$1" )
            shift
            ;;
    esac
done

cd $(git rev-parse --show-toplevel)

mkdir "${TEMPDIR}"
STAGE_DIR=$(mktemp -p "${TEMPDIR}" --directory)
if test ! -d "${STAGE_DIR}"; then
    rm -r "${TEMPDIR}"
    die "Failed to create staging directory"
fi

function repo_files() {
    # Why on earth git does not use the standard exlude rules for ls-files is
    # beyond me.
    # Note: We need the sort -u here because files may be repeated if they are
    # modified in the repo.
    git ls-files --exclude-standard -cmo | sort -u
}

echo "Building ashuffle archive..."
tar -cf "${STAGE_DIR}/ashuffle-archive.tar" --files-from=<( repo_files )

case "${IMAGE_BASE}" in
    ubuntu)
        args=( "${DOCKER_ARGS[@]}" )
        if test -n "${MPD_VERSION}"; then
            args+=( "--build-arg" "MPD_VERSION=${MPD_VERSION}" )
        fi
        if test -n "${LIBMPDCLIENT_VERSION}"; then
            args+=( "--build-arg" "LIBMPDCLIENT_VERSION=${LIBMPDCLIENT_VERSION}" )
        fi
        docker build "${args[@]}" --build-arg "STAGE_DIR=${STAGE_DIR}" \
            -t "${IMAGE_TAG}" -f ./t/docker/Dockerfile.ubuntu .
        ;;
    alpine)
        if test -n "${MPD_VERSION}" || test -n "${LIBMPDCLIENT_VERSION}"; then
            die "alpine does not support setting mpd/libmpdclient version"
        fi
        docker build --build-arg "STAGE_DIR=${STAGE_DIR}" \
            -t "${IMAGE_TAG}" -f ./t/docker/Dockerfile.alpine .
        ;;
    *)
        die "invalid image base: ${IMAGE_BASE}"
esac

rm -r "${STAGE_DIR}"
rmdir --ignore-fail-on-non-empty "${TEMPDIR}"
