#######################
##  Build Webserver  ##
#######################

FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:9.0 AS build-webserver
WORKDIR /WebServer

# Copy the csproj
COPY ./WebServer/WebServer.csproj ./

# Restore the Server
RUN dotnet restore './WebServer.csproj'

# Copy the rest of the backend over
COPY ./WebServer ./

# Build the source
RUN dotnet publish './WebServer.csproj' -c Release -o /app/publish

################
##  Publish   ##
################

FROM mcr.microsoft.com/dotnet/aspnet:9.0

# Pull in required libraries to build python from source
RUN apt update && apt upgrade -y && apt install -y \
    build-essential \
    zlib1g-dev \
    libncurses5-dev \
    libgdbm-dev \
    libnss3-dev \
    libssl-dev \
    libreadline-dev \
    libffi-dev \
    libsqlite3-dev \
    libbz2-dev \
    wget \
    ca-certificates \
    cron \
    && rm -rf /var/lib/apt/lists/*

# Download, extract, configure, and compile python 3.11
# Use Hardlinks and altinstall to not break system components that rely on the builtin python
RUN wget https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tgz && \
    tar -xf Python-3.11.0.tgz && \
    cd Python-3.11.0 && \
    ./configure --enable-optimizations --enable-shared && \
    make -j$(nproc) && \
    make altinstall && \
    # Cleanup
    cd .. && \
    rm -rf Python-3.11.0.tgz Python-3.11.0 && \
    # Tell the system where the new .so files are
    echo "/usr/local/lib" > /etc/ld.so.conf.d/python311.conf && \
    ldconfig && \
    # Create symlinks
    ln -s /usr/local/bin/python3.11 /usr/local/bin/python && \
    ln -s /usr/local/bin/pip3.11 /usr/local/bin/pip

RUN pip install --upgrade pip && \
    pip install tensorflow[and-cuda] \
    fastparquet \
    openpyxl \
    yfinance \
    matplotlib \
    scikit-learn

WORKDIR /app

ENV ASPNETCORE_HTTP_PORTS=5000
ENV StripeKey=null
ENV MySQLServer=null
ENV MySQLUser=null
ENV MySQLPass=null
ENV MySQLDatabase=Mistox

EXPOSE 5000

# Copy in the webserver
COPY --from=build-Webserver /app/publish ./

# Copy in cronjob
COPY crontab.txt /etc/cron.d/reload-finance-history

# Copy in EntryPoint
COPY entrypoint.sh /entrypoint.sh

# Give execution rights on the cronjob and entrypoint
RUN chmod 0644 /etc/cron.d/reload-finance-history && \
    chmod +x /entrypoint.sh && \
    touch /var/log/cron.log

# Apply the cron job
RUN crontab /etc/cron.d/reload-finance-history

# Start the container
ENTRYPOINT ["/entrypoint.sh"]