FROM artifactory.gz.cvte.cn/gitlab-cicd/golang:1.23-alpine AS builder

ARG VERSION=unknown

# set working directory
WORKDIR /app

# using goproxy if you have network issues
# ENV GOPROXY=https://goproxy.cn,direct

# copy go mod files first for better caching and dependency resolution
COPY go.mod go.sum ./
RUN go mod download

# copy project
COPY . .

# ensure go.mod is in sync with the source code
RUN go mod tidy

# build
RUN go build \
    -ldflags "\
    -X 'github.com/langgenius/dify-plugin-daemon/internal/manifest.VersionX=${VERSION}' \
    -X 'github.com/langgenius/dify-plugin-daemon/internal/manifest.BuildTimeX=$(date -u +%Y-%m-%dT%H:%M:%S%z)'" \
    -o /app/main cmd/server/main.go

# copy entrypoint.sh
COPY entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh

FROM artifactory.gz.cvte.cn/gitlab-cicd/ubuntu:24.04

WORKDIR /app

# check build args
ARG PLATFORM=local

# Install python3.12 if PLATFORM is local
RUN <<EOF bash

set -ex
set -o pipefail
trap 'echo "Exit status $? at line $LINENO from: $BASH_COMMAND"' ERR

apt-get update

DEBIAN_FRONTEND=noninteractive apt-get install -y curl python3.12 \
    python3.12-venv python3.12-dev python3-pip ffmpeg \
    build-essential git gcc g++ make \
    cmake pkg-config autoconf automake libtool \
    libcairo2-dev libjpeg-dev libgif-dev \
    libev4 libev-dev libevent-2.1-7 libevent-dev \
    libffi-dev libssl-dev zlib1g-dev

apt-get clean
rm -rf /var/lib/apt/lists/*
update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 1;
EOF

# preload tiktoken
ENV TIKTOKEN_CACHE_DIR=/app/.tiktoken

# Install dify_plugin to speedup the environment setup, test uv and preload tiktoken
RUN <<EOF bash

set -ex
set -o pipefail
trap 'echo "Exit status $? at line $LINENO from: $BASH_COMMAND"' ERR

mv /usr/lib/python3.12/EXTERNALLY-MANAGED /usr/lib/python3.12/EXTERNALLY-MANAGED.bk
python3 -m pip install uv
# 首先安装兼容的 Cython 版本以避免 gevent 编译失败
# Cython 3.1.0+ 移除了 long 类型支持,导致 gevent 编译错误
uv pip install --system 'Cython>=3.0.0,<3.1.0'
# 设置环境变量以确保 gevent 正确编译
export LIBEV_EMBED=false
export CFLAGS="-I/usr/include -O2"
export LDFLAGS="-L/usr/lib"
uv pip install --system dify_plugin

python3 -c "from uv._find_uv import find_uv_bin;print(find_uv_bin());"

python3 -c "import tiktoken; encodings = ['o200k_base', 'cl100k_base', 'p50k_base', 'r50k_base', 'p50k_edit', 'gpt2']; [tiktoken.get_encoding(encoding).special_tokens_set for encoding in encodings]"
EOF

ENV UV_PATH=/usr/local/bin/uv
ENV PLATFORM=$PLATFORM
ENV GIN_MODE=release

COPY --from=builder /app/main /app/entrypoint.sh /app/

# run the server, using sh as the entrypoint to avoid process being the root process
# and using bash to recycle resources
CMD ["/bin/bash", "-c", "/app/entrypoint.sh"]
