# Use Go 1.22 Alpine as the base image for building the application
FROM golang:1.22-alpine AS builder

# Install git, build tools and dependencies for Quirc
RUN apk add --no-cache git ca-certificates build-base make gcc musl-dev pkgconfig

# Build and install Quirc library (static library)
RUN cd /tmp && \
    git clone --depth 1 https://github.com/dlbeer/quirc.git && \
    cd quirc && \
    sed -i 's/\$(shell pkg-config --cflags sdl 2>&1)/\$(shell pkg-config --cflags sdl 2>\/dev\/null || true)/g' Makefile && \
    sed -i 's/\$(shell pkg-config --libs sdl)/\$(shell pkg-config --libs sdl 2>\/dev\/null || true)/g' Makefile && \
    sed -i 's/\$(shell pkg-config --cflags opencv4 2>&1)/\$(shell pkg-config --cflags opencv4 2>\/dev\/null || true)/g' Makefile && \
    sed -i 's/\$(shell pkg-config --libs opencv4)/\$(shell pkg-config --libs opencv4 2>\/dev\/null || true)/g' Makefile && \
    make libquirc.a && \
    mkdir -p /usr/local/lib /usr/local/include && \
    cp libquirc.a /usr/local/lib/ && \
    cp lib/quirc.h /usr/local/include/ && \
    ls -la /usr/local/lib/libquirc.a /usr/local/include/quirc.h && \
    rm -rf /tmp/quirc

# Define the base directory for the application as an environment variable
ENV SERVER_DIR=/openim-server
ENV CGO_ENABLED=1

# Set the working directory inside the container based on the environment variable
WORKDIR $SERVER_DIR

# Copy protocol directory
COPY protocol /protocol

# Copy current directory
COPY . .

RUN go mod tidy

# Build with static linking for Quirc (静态链接，运行时无需库文件)
# 使用 -ldflags 强制静态链接 Quirc 库和数学库
# 注意：Alpine Linux 使用 musl libc，需要静态链接数学库
RUN go build -tags cgo \
    -ldflags '-linkmode external -extldflags "-static -L/usr/local/lib -lquirc -lm"' \
    -o _output/openim-rpc-msg ./cmd/openim-rpc/openim-rpc-msg && \
    echo "构建完成，验证二进制文件..." && \
    file _output/openim-rpc-msg && \
    ldd _output/openim-rpc-msg 2>&1 | head -5 || echo "静态链接验证：二进制文件不依赖动态库（这是正常的）"


# Using Alpine Linux for the final image
FROM alpine:latest

# Install necessary packages, such as bash
RUN apk add --no-cache bash

# Set the environment and work directory
ENV SERVER_DIR=/openim-server
WORKDIR $SERVER_DIR


# Copy the compiled binaries and mage from the builder image to the final image
COPY --from=builder $SERVER_DIR/_output $SERVER_DIR/_output
# COPY --from=builder $SERVER_DIR/config $SERVER_DIR/config

# Set the command to run when the container starts
ENTRYPOINT ["sh", "-c", "_output/openim-rpc-msg"]
