ARG BASE_VERSION=24.04
ARG BASE_IMAGE=ubuntu:$BASE_VERSION

FROM ${BASE_IMAGE} AS documentserver
LABEL maintainer="ONLYOFFICE <support@onlyoffice.com>"
LABEL version="9.2.0"
LABEL description="ONLYOFFICE DocumentServer for ARM64 and AMD64"

ARG BASE_VERSION
ARG PG_VERSION=16
ARG PACKAGE_SUFFIX=t64

# Oracle Instant Client versions
ENV OC_RELEASE_NUM=23
ENV OC_RU_VER=7
ENV OC_RU_REVISION_VER=0
ENV OC_RESERVED_NUM=25
ENV OC_RU_DATE=01
ENV OC_PATH=${OC_RELEASE_NUM}${OC_RU_VER}0000
ENV OC_FILE_SUFFIX=${OC_RELEASE_NUM}.${OC_RU_VER}.${OC_RU_REVISION_VER}.${OC_RESERVED_NUM}.${OC_RU_DATE}
ENV OC_VER_DIR=${OC_RELEASE_NUM}_${OC_RU_VER}
ENV OC_DOWNLOAD_URL=https://download.oracle.com/otn_software/linux/instantclient/${OC_PATH}

# Locale and environment
ENV LANG=en_US.UTF-8 \
    LANGUAGE=en_US:en \
    LC_ALL=en_US.UTF-8 \
    DEBIAN_FRONTEND=noninteractive \
    PG_VERSION=${PG_VERSION} \
    BASE_VERSION=${BASE_VERSION}

# Company and product info
ARG COMPANY_NAME=onlyoffice
ARG PRODUCT_NAME=documentserver
ARG PRODUCT_EDITION=
ARG PACKAGE_VERSION=9.2.0
ARG TARGETARCH
ARG PACKAGE_BASEURL="http://download.onlyoffice.com/install/documentserver/linux"

ENV COMPANY_NAME=$COMPANY_NAME \
    PRODUCT_NAME=$PRODUCT_NAME \
    PRODUCT_EDITION=$PRODUCT_EDITION \
    DS_PLUGIN_INSTALLATION=false \
    DS_DOCKER_INSTALLATION=true

# ============================================
# HARDCODED CONFIGURATION - NO ENV VARS NEEDED
# ============================================
# Database Configuration
ENV DB_TYPE=postgres \
    DB_HOST=localhost \
    DB_PORT=5432 \
    DB_NAME=onlyoffice \
    DB_USER=onlyoffice \
    DB_PWD=onlyoffice

# Redis Configuration
ENV REDIS_SERVER_HOST=localhost \
    REDIS_SERVER_PORT=6379 \
    REDIS_ENABLED=true

# RabbitMQ Configuration
ENV AMQP_SERVER_HOST=localhost \
    AMQP_SERVER_PORT=5672 \
    AMQP_SERVER_USER=guest \
    AMQP_SERVER_PWD=guest \
    AMQP_SERVER_PROTO=amqp

# JWT Configuration (disabled by default)
ENV JWT_ENABLED=false \
    JWT_SECRET=secret \
    JWT_HEADER=Authorization \
    JWT_IN_BODY=false

# Other settings
ENV WOPI_ENABLED=false \
    GENERATE_FONTS=true \
    METRICS_ENABLED=false \
    PLUGINS_ENABLED=true \
    DS_LOG_LEVEL=WARN

# Create policy to allow services to start
RUN echo "#!/bin/sh\nexit 0" > /usr/sbin/policy-rc.d

# Install base packages
RUN apt-get -y update && \
    apt-get -yq install \
        wget \
        apt-transport-https \
        gnupg \
        locales \
        lsb-release && \
    locale-gen en_US.UTF-8

# Add Microsoft repository for SQL tools
RUN wget -q -O /etc/apt/sources.list.d/mssql-release.list \
        "https://packages.microsoft.com/config/ubuntu/$BASE_VERSION/prod.list" && \
    wget -q -O /tmp/microsoft.asc https://packages.microsoft.com/keys/microsoft.asc && \
    apt-key add /tmp/microsoft.asc && \
    gpg --dearmor -o /usr/share/keyrings/microsoft-prod.gpg < /tmp/microsoft.asc

# Accept Microsoft fonts EULA
RUN echo ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true | debconf-set-selections

# Install all required packages
RUN apt-get -y update && \
    ACCEPT_EULA=Y apt-get -yq install \
        adduser \
        apt-utils \
        bomstrip \
        certbot \
        cron \
        curl \
        htop \
        libaio1${PACKAGE_SUFFIX} \
        libasound2${PACKAGE_SUFFIX} \
        libboost-regex-dev \
        libcairo2 \
        libcurl3-gnutls \
        libcurl4 \
        libgtk-3-0 \
        libnspr4 \
        libnss3 \
        libstdc++6 \
        libxml2 \
        libxss1 \
        libxtst6 \
        mssql-tools18 \
        mysql-client \
        nano \
        net-tools \
        netcat-openbsd \
        nginx-extras \
        postgresql \
        postgresql-client \
        pwgen \
        rabbitmq-server \
        redis-server \
        sudo \
        supervisor \
        ttf-mscorefonts-installer \
        unixodbc-dev \
        unzip \
        xvfb \
        xxd \
        zlib1g || dpkg --configure -a

# Verify Microsoft fonts installation
RUN if [ $(find /usr/share/fonts/truetype/msttcorefonts -maxdepth 1 -type f -iname '*.ttf' | wc -l) -lt 30 ]; then \
        echo 'msttcorefonts failed to download'; exit 1; \
    fi

# Configure RabbitMQ for single CPU
RUN echo "SERVER_ADDITIONAL_ERL_ARGS=\"+S 1:1\"" | tee -a /etc/rabbitmq/rabbitmq-env.conf

# Configure Redis to bind to localhost only
RUN sed -i "s/bind .*/bind 127.0.0.1/g" /etc/redis/redis.conf

# Add wasm mime type to nginx
RUN sed 's|\(application\/zip.*\)|\1\n    application\/wasm wasm;|' -i /etc/nginx/mime.types

# Configure PostgreSQL
RUN pg_conftool $PG_VERSION main set listen_addresses 'localhost'

# Start PostgreSQL and create user/database
RUN service postgresql restart && \
    sudo -u postgres psql -c "CREATE USER ${DB_USER} WITH password '${DB_PWD}';" && \
    sudo -u postgres psql -c "CREATE DATABASE ${DB_NAME} OWNER ${DB_USER};"

# Download and install Oracle Instant Client (architecture-specific)
RUN wget -O basic.zip ${OC_DOWNLOAD_URL}/instantclient-basic-linux.$(dpkg --print-architecture | sed 's/amd64/x64/')-${OC_FILE_SUFFIX}.zip && \
    wget -O sqlplus.zip ${OC_DOWNLOAD_URL}/instantclient-sqlplus-linux.$(dpkg --print-architecture | sed 's/amd64/x64/')-${OC_FILE_SUFFIX}.zip && \
    unzip -o basic.zip -d /usr/share && \
    unzip -o sqlplus.zip -d /usr/share && \
    mv /usr/share/instantclient_${OC_VER_DIR} /usr/share/instantclient && \
    find /usr/lib /lib -name "libaio.so.1$PACKAGE_SUFFIX" -exec bash -c 'ln -sf "$0" "$(dirname "$0")/libaio.so.1"' {} \; && \
    rm -f basic.zip sqlplus.zip

# Stop services that were started during build
RUN service postgresql stop && \
    service redis-server stop && \
    service rabbitmq-server stop && \
    service supervisor stop && \
    service nginx stop

# Clean up apt cache
RUN rm -rf /var/lib/apt/lists/*

# Copy configuration files
COPY config/supervisor/supervisor /etc/init.d/
COPY config/supervisor/ds/*.conf /etc/supervisor/conf.d/
COPY run-document-server.sh /app/ds/run-document-server.sh

# Create sqlplus wrapper
RUN mkdir -p /usr/bin && \
    echo '#!/bin/bash' > /usr/bin/sqlplus && \
    echo 'export LD_LIBRARY_PATH=/usr/share/instantclient:$LD_LIBRARY_PATH' >> /usr/bin/sqlplus && \
    echo 'exec /usr/share/instantclient/sqlplus "$@"' >> /usr/bin/sqlplus && \
    chmod +x /usr/bin/sqlplus

# Expose ports
EXPOSE 80 443

# Download and install ONLYOFFICE DocumentServer package
RUN PACKAGE_FILE="${COMPANY_NAME}-${PRODUCT_NAME}${PRODUCT_EDITION}${PACKAGE_VERSION:+_$PACKAGE_VERSION}_${TARGETARCH:-$(dpkg --print-architecture)}.deb" && \
    echo "Downloading package: $PACKAGE_BASEURL/$PACKAGE_FILE" && \
    wget -q -P /tmp "$PACKAGE_BASEURL/$PACKAGE_FILE" && \
    apt-get -y update && \
    service postgresql start && \
    apt-get -yq install /tmp/$PACKAGE_FILE && \
    # Clean up temp database used during installation
    PGPASSWORD=$DB_PWD dropdb -h localhost -p 5432 -U $DB_USER $DB_NAME 2>/dev/null || true && \
    sudo -u postgres psql -c "DROP ROLE IF EXISTS ${DB_USER};" 2>/dev/null || true && \
    service postgresql stop && \
    chmod 755 /etc/init.d/supervisor && \
    sed "s/COMPANY_NAME/${COMPANY_NAME}/g" -i /etc/supervisor/conf.d/*.conf && \
    service supervisor stop && \
    chmod 755 /app/ds/*.sh && \
    # Add GO command for MSSQL scripts
    printf "\nGO" >> "/var/www/$COMPANY_NAME/documentserver/server/schema/mssql/createdb.sql" && \
    printf "\nGO" >> "/var/www/$COMPANY_NAME/documentserver/server/schema/mssql/removetbl.sql" && \
    # Add exit command for Oracle scripts
    printf "\nexit" >> "/var/www/$COMPANY_NAME/documentserver/server/schema/oracle/createdb.sql" && \
    printf "\nexit" >> "/var/www/$COMPANY_NAME/documentserver/server/schema/oracle/removetbl.sql" && \
    rm -f /tmp/$PACKAGE_FILE && \
    rm -rf /var/log/$COMPANY_NAME && \
    rm -rf /var/lib/apt/lists/*

# Define volumes for persistent data
VOLUME /var/log/$COMPANY_NAME \
       /var/lib/$COMPANY_NAME \
       /var/www/$COMPANY_NAME/Data \
       /var/lib/postgresql \
       /var/lib/rabbitmq \
       /var/lib/redis \
       /usr/share/fonts/truetype/custom

# Set entrypoint
ENTRYPOINT ["/app/ds/run-document-server.sh"]
