ARG KUBERNETES_HOST=${KUBERNETES_HOST:-"127.0.0.1"}

FROM golang:alpine AS deps

WORKDIR /app
COPY go.mod go.sum ./
RUN sed -i '/replace/d' go.mod
RUN go mod download

#----------------------------------------------------------------------------------------------

FROM golang:alpine AS builder

WORKDIR /app 

RUN apk add git

RUN go install github.com/beego/bee/v2@latest

WORKDIR /oc-datacenter

COPY --from=deps /go/pkg /go/pkg
COPY --from=deps /app/go.mod /app/go.sum ./

RUN export CGO_ENABLED=0 && \
    export GOOS=linux && \
    export GOARCH=amd64 && \
    export BUILD_FLAGS="-ldflags='-w -s'"

COPY . .

RUN sed -i '/replace/d' go.mod
RUN if [ ! -f swagger/index.html ]; then timeout 15 bee run -gendoc=true -downdoc=true; fi
RUN bee generate routers
RUN bee generate docs
RUN bee pack
RUN mkdir -p /app/extracted && tar -zxvf oc-datacenter.tar.gz -C /app/extracted
RUN sed -i 's/http:\/\/127.0.0.1:8080\/swagger\/swagger.json/swagger.json/g' /app/extracted/swagger/index.html

#----------------------------------------------------------------------------------------------

FROM golang:alpine

ENV KUBERNETES_SERVICE_HOST=$KUBERNETES_HOST

WORKDIR /app
COPY --from=builder /app/extracted/oc-datacenter /usr/bin/ 
COPY --from=builder /app/extracted/swagger /app/swagger
COPY --from=builder /app/extracted/docker_datacenter.json /etc/oc/datacenter.json

EXPOSE 8080

ENTRYPOINT ["oc-datacenter"]
