#
#    LEAN Jupyter Docker Container 20190428
#

# Use base system for cleaning up wayward processes
ARG LEAN_TAG=latest
FROM quantconnect/lean:$LEAN_TAG

MAINTAINER QuantConnect <contact@quantconnect.com>

# Install Tini
RUN wget --quiet https://github.com/krallin/tini/releases/download/v0.10.0/tini && \
    echo "1361527f39190a7338a0b434bd8c88ff7233ce7b9a4876f3315c22fce7eca1b0 *tini" | sha256sum -c - && \
    mv tini /usr/local/bin/tini && \
    chmod +x /usr/local/bin/tini

# Clone Lean; Copy Python startup file to profile; Install Lean/PythonToolbox; Remove extra files
RUN git clone https://github.com/QuantConnect/Lean.git && \
    mkdir -p /root/.ipython/profile_default/startup/ && cp -f Lean/Research/start.py /root/.ipython/profile_default/startup/ && \
    cd Lean/PythonToolbox && python setup.py install \
    && cd ../.. && rm -irf Lean

RUN conda install -y -c conda-forge notebook=6.0.3

#Install ICSharp (Jupyter C# Kernel)
RUN wget https://cdn.quantconnect.com/icsharp/ICSharp.Kernel.20180820.zip && \
    unzip ICSharp.Kernel.20180820.zip -d / && rm -irf ICSharp.Kernel.20180820.zip && cd /icsharp && \
    jupyter kernelspec install kernel-spec --name=csharp

# Setting some environment variables
ENV WORK /Lean/Launcher/bin/Debug/
ENV PYTHONPATH=${WORK}:${PYTHONPATH}

RUN find ${WORK} -type f -not -name '*.py*' -not -name '*.xml' -not -name '*.exe.config' -not -name '*.exe' -not -name '*.so' -not -name '*.dll' -not -name '*.ipynb' -not -name '*.csx' -not -name 'decimal.py' -delete

#Create initialize script
RUN echo "if [ ! -d \"${WORK}Notebooks\" ]; then mkdir ${WORK}Notebooks; fi && \
    if [ ! -f \"${WORK}Notebooks/config.json\" ]; then echo '{ \"data-folder\": \"/home/Data/\", \
    \"composer-dll-directory\": \"$WORK\", \"algorithm-language\": \"Python\", \
    \"messaging-handler\": \"QuantConnect.Messaging.Messaging\", \"job-queue-handler\": \"QuantConnect.Queues.JobQueue\", \
    \"api-handler\": \"QuantConnect.Api.Api\" }' > ${WORK}Notebooks/config.json; fi && \
    echo \"Starting Jupter lab, access in your browser at localhost:8888\" && \
    jupyter lab --ip='0.0.0.0' --port=8888 --no-browser --allow-root --notebook-dir=\"Notebooks\" --LabApp.token='' " \
    > start.sh

# We keep this pythonnet used for C# -> Py (C# kernels)
# We copy the pythonnet used for the Py kernels
RUN mkdir ${WORK}pythonnet && \
    mv -f ${WORK}Python.Runtime.dll ${WORK}pythonnet/Python.Runtime.dll && \
    mv -f ${WORK}jupyter/* ${WORK} && \
    chmod -R 777 ${WORK}

EXPOSE 8888
WORKDIR $WORK

ENTRYPOINT [ "/usr/local/bin/tini", "--" ]
CMD ./start.sh