FROM devtools/go-toolset-rhel7:1.12 AS builder

ENV GOPATH=/tmp/go
ENV PROJECT_NAME="apicast-operator"
ENV OUTPUT_DIR="/tmp/_output"
ENV BINARY_NAME="${PROJECT_NAME}"
ENV REPO_PATH="github.com/3scale"
ENV REPO_SRC_PATH="src/${REPO_PATH}"
ENV BUILD_PATH="${REPO_PATH}/${PROJECT_NAME}/cmd/manager"

ARG OPERATOR_VENDOR_TARBALL=vendor-${PROJECT_NAME}.tar.gz
ARG OPERATOR_LICENSES_TARBALL=licenses-apicast-operator.tar.gz

# get and uncompress operator source code
# We copy and then uncompress with tar instead of
# using the ADD statement due to 'imagebuilder' that
# is used in brew does not expand archives when using
# the ADD statement. See issue:
# https://github.com/openshift/imagebuilder/issues/99
COPY ${PROJECT_NAME}-*.tar.gz /tmp

# get and uncompress operator vendored modules
COPY ${OPERATOR_VENDOR_TARBALL} /tmp

RUN mkdir -p ${GOPATH}/${REPO_SRC_PATH}
WORKDIR ${GOPATH}

# Move uncompressed files to the GOPATH source code location
# to prepare it for the build
RUN tar -C ${GOPATH}/${REPO_SRC_PATH} -xzf /tmp/${PROJECT_NAME}-*.tar.gz
RUN mv ${REPO_SRC_PATH}/${PROJECT_NAME}{-*,}
RUN tar -C ${GOPATH}/${REPO_SRC_PATH}/${PROJECT_NAME} -xzf /tmp/${OPERATOR_VENDOR_TARBALL}

RUN mkdir -p ${OUTPUT_DIR}
RUN echo "build path: ${BUILD_PATH}"
RUN echo "output path: ${OUTPUT_DIR}"

# Uncompress sand move licenses to output directory
COPY ${OPERATOR_LICENSES_TARBALL} /tmp
RUN tar -C ${OUTPUT_DIR} -xzf /tmp/${OPERATOR_LICENSES_TARBALL}

# We enable go-toolset-1.12 because it sets/modifies some environment
# variables like PATH. If we don't do this the go binary cannot be found
RUN scl enable go-toolset-1.12 "GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o ${OUTPUT_DIR}/${PROJECT_NAME} ${BUILD_PATH}"

FROM ubi7-minimal:7-released
# Labels consumed by Red Hat build service
LABEL com.redhat.component="3scale-apicast-operator-container" \
      name="3scale-amp2/apicast-rhel7-operator" \
      version="1.11" \
      summary="APIcast operator container image" \
      description="APIcast Operator provides an easy way to install a 3scale APIcast self-managed solution, providing configurability options at the time of installation." \
      io.k8s.display-name="APIcast Operator" \
      io.openshift.expose-services="" \
      io.openshift.tags="3scale, apicast, api, gateway, openresty, api-gateway" \
      maintainer="msoriano@redhat.com"


ENV OPERATOR=/usr/local/bin/apicast-operator \
    USER_UID=1001 \
    USER_NAME=apicast-operator

# install operator binary
COPY --from=builder /tmp/_output/apicast-operator /usr/local/bin/

# install licenses
COPY --from=builder /tmp/_output/licenses.xml /root/licenses/apicast-operator/

COPY user_setup /usr/local/bin
COPY entrypoint /usr/local/bin
RUN  /usr/local/bin/user_setup

ENTRYPOINT ["/usr/local/bin/entrypoint"]

USER ${USER_UID}
