# ============================================================
# Genex Chain — Multi-stage Docker Build
# ============================================================
# 基于 cosmos/evm v0.5.1, Cosmos SDK v0.53.5, CometBFT v0.38.19
#
# 用法:
#   docker build -t genex-chain:latest .
#   docker run -p 26657:26657 -p 8545:8545 genex-chain:latest
# ============================================================

# ========================
# Stage 1: Builder
# ========================
FROM golang:1.23-alpine AS builder

RUN apk add --no-cache \
    make \
    gcc \
    musl-dev \
    linux-headers \
    git \
    bash \
    curl

WORKDIR /build

# Copy go.mod first for dependency caching
COPY go.mod ./
RUN go mod download 2>/dev/null || true

# Copy source code
COPY . .

# Resolve all dependencies
RUN go mod tidy

# Build the binary with CGO (required for Cosmos SDK crypto)
RUN CGO_ENABLED=1 GOOS=linux go build \
    -ldflags "-X github.com/cosmos/cosmos-sdk/version.Name=GenexChain \
              -X github.com/cosmos/cosmos-sdk/version.AppName=genexd \
              -X github.com/cosmos/cosmos-sdk/version.Version=1.0.0 \
              -X github.com/cosmos/cosmos-sdk/version.Commit=$(git rev-parse --short HEAD 2>/dev/null || echo 'dev') \
              -X github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger \
              -w -s" \
    -tags "netgo,ledger" \
    -trimpath \
    -o /build/bin/genexd \
    ./cmd/genexd/

# ========================
# Stage 2: Runtime
# ========================
FROM alpine:3.19

RUN apk add --no-cache \
    ca-certificates \
    bash \
    curl \
    jq

# Create non-root user
RUN addgroup -S genex && adduser -S genex -G genex

# Copy binary from builder
COPY --from=builder /build/bin/genexd /usr/local/bin/genexd

# Copy initialization scripts
COPY scripts/ /opt/genex/scripts/

RUN chmod +x /usr/local/bin/genexd && \
    chmod +x /opt/genex/scripts/*.sh 2>/dev/null || true

# Set up data directory
RUN mkdir -p /home/genex/.genexd && \
    chown -R genex:genex /home/genex

USER genex
WORKDIR /home/genex

# Expose ports
# P2P: 26656, RPC: 26657, EVM JSON-RPC: 8545, EVM WS: 8546
# REST API: 1317, gRPC: 9090, gRPC-web: 9091
EXPOSE 26656 26657 8545 8546 1317 9090 9091

# Health check
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
    CMD curl -f http://localhost:26657/status || exit 1

ENTRYPOINT ["genexd"]
CMD ["start"]
