ARG REGISTRY=docker.io
FROM ${REGISTRY}/golang:1.24-alpine AS builder
RUN set -eux && sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories

# 定义应用路径参数，用于指定构建的入口文件路径
ARG APP_RELATIVE_PATH
# 定义应用名称参数，用于指定输出的二进制文件名
ARG APP_NAME=app

# 先复制依赖文件，利用缓存层
WORKDIR /data/app
COPY go.mod go.sum /data/app/
RUN export GOPROXY=https://goproxy.cn,direct && go mod download

# 再复制其他文件
COPY . /data/app/

RUN mkdir -p /data/app/bin/
RUN export GOPROXY=https://goproxy.cn,direct && go mod tidy && go build -ldflags="-s -w" -o ./bin/${APP_NAME} ${APP_RELATIVE_PATH}
RUN mv config /data/app/bin/


FROM ${REGISTRY}/alpine:3.16
RUN set -eux && sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories


RUN apk add tzdata && cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
    && echo "Asia/Shanghai" > /etc/timezone \
    && apk del tzdata


ARG APP_ENV
ENV APP_ENV=${APP_ENV}
# 传递应用名称到运行环境
ARG APP_NAME=app
ENV APP_NAME=${APP_NAME}

WORKDIR /data/app
COPY --from=builder /data/app/bin /data/app

# 仅对server应用暴露端口
EXPOSE 8000
# 在构建阶段设置ENTRYPOINT，支持通过APP_CONF环境变量指定配置文件
RUN echo '#!/bin/sh' > /data/app/entrypoint.sh && \
    echo 'if [ ! -z "$APP_CONF" ]; then' >> /data/app/entrypoint.sh && \
    echo '  echo "Using config from APP_CONF: $APP_CONF"' >> /data/app/entrypoint.sh && \
    echo 'fi' >> /data/app/entrypoint.sh && \
    echo 'exec ./'${APP_NAME}' "$@"' >> /data/app/entrypoint.sh && \
    chmod +x /data/app/entrypoint.sh
ENTRYPOINT [ "./entrypoint.sh" ]

# 构建server应用示例
#docker build -t 1.1.1.1:5000/demo-api:v1 --build-arg APP_NAME=app --build-arg APP_RELATIVE_PATH=./cmd/server/main.go .

# 构建task应用示例
#docker build -t 1.1.1.1:5000/demo-task:v1 --build-arg APP_NAME=task --build-arg APP_RELATIVE_PATH=./cmd/task/main.go .

# 运行容器测试示例
#docker run -it --rm --entrypoint=ash 1.1.1.1:5000/demo-api:v1
