#!/bin/bash
set -e

# Setup SSH
setup_ssh() {
    mkdir -p /var/run/sshd
    ssh-keygen -A
    service ssh start || /usr/sbin/sshd
}

# Start Jupyter Lab
start_jupyter() {
    local TOKEN=${JUPYTER_PASSWORD:-crowdcent}
    mkdir -p /workspace
    # Trust notebooks so HTML renders (sklearn diagrams, etc.)
    /app/.venv/bin/jupyter trust /workspace/*.ipynb 2>/dev/null || true
    cd /
    nohup /app/.venv/bin/python -m jupyter lab \
        --allow-root --no-browser --port=8888 --ip=0.0.0.0 \
        --FileContentsManager.delete_to_trash=False \
        --FileContentsManager.preferred_dir=/workspace \
        --IdentityProvider.token="$TOKEN" \
        --ServerApp.allow_origin='*' \
        &> /var/log/jupyter.log &
}

echo "--- Starting CrowdCent Pod ---"
setup_ssh
start_jupyter
echo "Jupyter started on port 8888 (token: ${JUPYTER_PASSWORD:-crowdcent})"
sleep infinity
