# --- Build Image ---
FROM golang:1.25 AS builder

WORKDIR /build

COPY go.mod go.sum ./
RUN go mod download

COPY . ./
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o server ./cmd/cyberia-server/

# --- Runtime Image ---
FROM rockylinux/rockylinux:9 AS runtime
ARG NODE_VERSION=24.15.0

RUN set -eux; \
    dnf install -y git tar xz; \
    arch="$(uname -m)"; \
    case "$arch" in \
      x86_64) node_arch=x64 ;; \
      aarch64) node_arch=arm64 ;; \
      *) echo "unsupported arch: $arch" >&2; exit 1 ;; \
    esac; \
    curl -fsSL "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-${node_arch}.tar.xz" \
      | tar -xJ -C /usr/local --strip-components=1; \
    node --version; npm --version; \
    dnf clean all; rm -rf /var/cache/dnf


COPY underpost-cli.tgz /tmp/underpost-cli.tgz
RUN set -eux; \
    npm install -g /tmp/underpost-cli.tgz --omit=dev; \
    rm -f /tmp/underpost-cli.tgz; \
    npm cache clean --force; \
    underpost --version

# Path is the contract with conf.instances.json mmo-server cmd, which execs
# /home/dd/engine/cyberia-server/server in both development and production.
# Keep this identical to Dockerfile.dev so prod and dev images are interchangeable.
WORKDIR /home/dd/engine/cyberia-server

COPY --from=builder /build/server ./server

COPY public/ ./public/

EXPOSE 8081

# Both Data Server endpoints are flags, not environment reads (cmd/cyberia-server/main.go), and
# the server refuses to start without them. Passing them here from the environment is what lets a
# plain `docker run` or a Compose service that sets no command still start: a Kubernetes pod spec
# supplies its own command and overrides this. An empty CYBERIA_PUBLIC_URL keeps the server off
# the Data Server registry.
ENV CYBERIA_DATA_SERVER_URL=http://engine-cyberia
ENV CYBERIA_DATA_SERVER_GRPC=engine-cyberia-runtime:50051
ENV CYBERIA_PUBLIC_URL=

CMD ["sh", "-c", "exec /home/dd/engine/cyberia-server/server --data-server-url=${CYBERIA_DATA_SERVER_URL} --data-server-grpc=${CYBERIA_DATA_SERVER_GRPC} --game-server-public-url=${CYBERIA_PUBLIC_URL}"]
