# syntax=docker/dockerfile:1.11.1

#######################################################################
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openFuyao is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
#######################################################################

ARG BUILDER=golang
ARG BUILDER_VERSION=1.24.5-oe-24.03-lts-sp3
# Use the prebuilt openFuyao builder image to reduce build time.
ARG BUILDER_IMAGE=cr.openfuyao.cn/openfuyao/$BUILDER:$BUILDER_VERSION
ARG K8S_VER=1.0

# stage 1: build
FROM ${BUILDER_IMAGE} AS build
USER 0
WORKDIR /go/src/app
COPY . .

RUN --mount=type=cache,target=/go/pkg/mod,sharing=locked \
    <<'EOF'
#!/bin/bash -xeu
# 1. 创建目标头文件目录
mkdir -p /usr/include/ubse/

# 2. 从 ADD 进来的目录中,将头文件拷贝到指定位置

# 3. 配置 CGO 环境变量,相当于给 gcc 传递 -I 参数

# 4. 执行原始的安全加固编译逻辑
export KUBE_TAG="1.34.3-of.1"
export CLIENT_GO_VERSION="-X 'k8s.io/client-go/pkg/version.getVersion=${KUBE_TAG}'"
export COMPONENT_BASE_VERSION="-X 'k8s.io/component-base/version.getVersion=${KUBE_TAG}'"
export GO_BUILD_FLAGS='-v -tags=container -buildmode=pie -a -trimpath'
export LDFLAGS='-w -s -buildid none -linkmode=external -extldflags "-Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack"'
export GOPROXY="https://goproxy.cn,https://goproxy.io,direct"
export GOPRIVATE="atomgit.com"
export GONOPROXY="atomgit.com"
export GONOSUMDB="atomgit.com"
git config --global url."https://atomgit.com/".insteadOf "atomgit.com/"
go mod tidy
cd cmd/matrixcontroller
CGO_ENABLED=1 CC=gcc go build ${GO_BUILD_FLAGS} -o /home/nonroot/matrixcontroller -ldflags "${CLIENT_GO_VERSION} ${COMPONENT_BASE_VERSION} ${LDFLAGS}"
EOF

# stage 2: release
FROM hub.oepkgs.net/openeuler/openeuler:24.03-lts-sp1 AS release
WORKDIR /
ENV PATH="/:${PATH}"
RUN dnf install -y shadow-utils && dnf clean all
COPY --link --from=build --chmod=500 /home/nonroot/matrixcontroller /usr/local/bin/matrixcontroller
RUN /usr/sbin/useradd -u 4177 matrixplugin -m -s /sbin/nologin \
    && chown matrixplugin:matrixplugin /usr/local/bin/matrixcontroller \
    && dnf remove -y shadow-utils && dnf clean all
USER matrixplugin
ENTRYPOINT ["/usr/local/bin/matrixcontroller"]