FROM ubi8-minimal:8-released

USER root

# Set TZ to avoid glibc wasting time with unneeded syscalls
ENV TZ=:/etc/localtime \
    HOME=/tmp/ \
    GOPATH=/go
ENV PATH="${PATH}:${GOPATH}/bin"

ARG VENDOR_PKGS="tar gzip git go-toolset make perl-Digest-SHA"

ARG PROJECT_NAME
ARG REPO
ARG TAG

RUN microdnf update --nodocs --setopt=tsflags=nodocs -y \
 && microdnf install --nodocs --setopt=tsflags=nodocs -y ${VENDOR_PKGS} \
 && microdnf clean all -y \
 && rm -rf /var/cache/yum

ARG DEP_VERSION=v0.5.3

RUN mkdir -p "${GOPATH}/bin" "${GOPATH}/src/github.com/"{3scale,golang} \
 && cd "${GOPATH}/src/github.com/golang" \
 && git clone --recurse-submodules --shallow-submodules --depth 1 \
      --branch ${DEP_VERSION} --single-branch --jobs $(nproc) \
      https://github.com/golang/dep.git dep \
 && cd dep \
 && echo "This checkout is $(git describe --dirty --tags)"

RUN cd "${GOPATH}/src/github.com/golang/dep" \
 && make install

RUN git clone --recurse-submodules --shallow-submodules --depth 1 \
      --branch ${TAG} --single-branch --jobs $(nproc) ${REPO} \
      "${GOPATH}/src/github.com/3scale/${PROJECT_NAME}" \
 && cd "${GOPATH}/src/github.com/3scale/${PROJECT_NAME}" \
 && echo "This checkout is $(git describe --dirty --tags)"

RUN cd "${GOPATH}/src/github.com/3scale/${PROJECT_NAME}" \
 && dep ensure \
 && if git diff-files --quiet; then \
      echo "Vendoring modifies dependencies data from the archive, fix upstream" ; \
      git status ; \
      false ; \
    fi \
 && if ! git ls-files --other --exclude-standard --error-unmatch; then \
      echo "Untracked and unignored files present when vendoring, aborting" ; \
      git status ; \
      false ; \
    fi \
 && git archive --format=tar --prefix=${PROJECT_NAME}-${TAG}/ \
      -o /tmp/${PROJECT_NAME}-${TAG}.tar ${TAG} \
 && ARCHIVE_SIZE="$(stat --printf=%s /tmp/${PROJECT_NAME}-${TAG}.tar)" \
 && tar rf /tmp/${PROJECT_NAME}-${TAG}.tar \
      --transform=s,^\\.,${PROJECT_NAME}-${TAG}, ./vendor \
 && rm -rf "${GOPATH}/src/github.com/3scale/${PROJECT_NAME}" \
 && FULL_SIZE="$(stat --printf=%s /tmp/${PROJECT_NAME}-${TAG}.tar)" \
 && VENDOR_SIZE="$(expr ${FULL_SIZE} - ${ARCHIVE_SIZE})" \
 && gzip -9 /tmp/${PROJECT_NAME}-${TAG}.tar \
 && TARBALL_SIZE="$(stat --printf=%s /tmp/${PROJECT_NAME}-${TAG}.tar.gz)" \
 && /bin/echo -e "\n* Uncompressed size:\n" \
    "    Sources -> ${ARCHIVE_SIZE}" \
    "($(numfmt --to=iec-i --suffix=B --format=%f ${ARCHIVE_SIZE})) " \
    "+ Dependencies -> ${VENDOR_SIZE}" \
    "($(numfmt --to=iec-i --suffix=B --format=%f ${VENDOR_SIZE})) " \
    "= ${FULL_SIZE}" \
    "($(numfmt --to=iec-i --suffix=B --format=%f ${FULL_SIZE}))\n" \
    "* Vendored tarball:\n" \
    "    ${PROJECT_NAME}-${TAG}.tar.gz -> ${TARBALL_SIZE}" \
    "($(numfmt --to=iec-i --suffix=B --format=%f ${TARBALL_SIZE}))\n"
