FROM ubuntu:22.04

# Install dependencies
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        ca-certificates \
        curl \
        file \
    && rm -rf /var/lib/apt/lists/*

# Create data directory
RUN mkdir -p /app/data

WORKDIR /app

# Download and extract Corteza
ARG CORTEZA_VERSION=2022.9.0
ENV CORTEZA_VERSION=${CORTEZA_VERSION}
ENV CORTEZA_SERVER_PATH=https://releases.cortezaproject.org/files/corteza-server-${CORTEZA_VERSION}-linux-amd64.tar.gz
ENV CORTEZA_WEBAPP_PATH=https://releases.cortezaproject.org/files/corteza-webapp-${CORTEZA_VERSION}.tar.gz

RUN curl -sL $CORTEZA_SERVER_PATH -o /tmp/corteza-server.tar.gz && \
    tar zxvf /tmp/corteza-server.tar.gz -C /app && \
    curl -sL $CORTEZA_WEBAPP_PATH -o /tmp/corteza-webapp.tar.gz && \
    tar zxvf /tmp/corteza-webapp.tar.gz -C /app/corteza/webapp && \
    rm /tmp/corteza-server.tar.gz /tmp/corteza-webapp.tar.gz && \
    mv /app/corteza-server /app/corteza-server && \
    mv /app/corteza-server /app/corteza-server 2>/dev/null || true

# Set environment
ENV STORAGE_PATH="/app/data"
ENV CORREDOR_ADDR="127.0.0.1:5432"
ENV HTTP_ADDR="0.0.0.0:80"
ENV HTTP_WEBAPP_ENABLED="true"
ENV HTTP_WEBAPP_BASE_DIR="/app/corteza/webapp"

# Expose port
EXPOSE 80

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
    CMD curl -f http://localhost:80/healthcheck || exit 1

# Start Corteza
ENTRYPOINT ["./corteza-server/bin/corteza-server"]
CMD ["serve-api"]
