#@follow_tag(registry.redhat.io/devtools/go-toolset-rhel7:1.13)
FROM registry.redhat.io/devtools/go-toolset-rhel7:1.13.15-4 AS builder

ENV PROJECT_NAME="3scale-operator"
ENV OUTPUT_DIR="/tmp/_output"
ENV BINARY_NAME="manager"
ENV BUILD_PATH="${REMOTE_SOURCE_DIR}/app"

WORKDIR ${BUILD_PATH}

# Copy the upstream sources from cachito integration
COPY $REMOTE_SOURCE $REMOTE_SOURCE_DIR

# Add patches to image and apply patches, in order.
ADD patches /tmp/patches
RUN find /tmp/patches -type f -name '*.patch' -print0 | sort --zero-terminated | xargs -t -0 -n 1 patch --force -p1

USER root

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

# We enable go-toolset-1.13 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.13 "GOOS=linux GOARCH=$(scl enable go-toolset-1.13 'go env GOARCH') CGO_ENABLED=0 GO111MODULE=on go build -o ${OUTPUT_DIR}/${BINARY_NAME} main.go"

# Copy licenses
RUN mkdir ${OUTPUT_DIR}/licenses/
RUN cp "./licenses.xml" "${OUTPUT_DIR}/licenses/"

#@follow_tag(registry.redhat.io/ubi7/ubi-minimal:latest)
FROM registry.redhat.io/ubi7/ubi-minimal:7.9-778

# Labels consumed by Red Hat build service
LABEL com.redhat.component="3scale-operator-container" \
    name="3scale-amp2/3scale-rhel7-operator" \
    version="1.15.0"\
    summary="3scale Operator container image" \
    description="Operator provides a way to install a 3scale API Management and ability to define 3scale API definitions." \
    io.k8s.display-name="3scale Operator" \
    io.openshift.expose-services="" \
    io.openshift.tags="3scale, 3scale-amp, api" \
    maintainer="eastizle@redhat.com"

ENV OPERATOR_BINARY_NAME="manager" \
  USER_UID=1001 \
  USER_NAME=3scale-operator

USER root

# install operator binary
COPY --from=builder /tmp/_output/${OPERATOR_BINARY_NAME} /
RUN chown ${USER_UID} /${OPERATOR_BINARY_NAME}

# Install licenses
ENV LICENSES_DIR="/root/licenses/3scale-operator/"
RUN mkdir -p ${LICENSES_DIR}
COPY --from=builder /tmp/_output/licenses/licenses.xml ${LICENSES_DIR}
RUN chown ${USER_UID} ${LICENSES_DIR}/licenses.xml

ENTRYPOINT ["/manager"]

USER ${USER_UID}
