#! /usr/bin/env sh

# Arguments to this script are passed to the 'jupyter notebook' command. Run
# with `--ip=<public ip>` to share the demo over the network.

set -euo pipefail

repository="$(git rev-parse --show-toplevel)"

PATH="${repository}/build/bin:${PATH}"
if ! >/dev/null 2>&1 command -v vast; then
  >&2 echo "Cannot find vast in PATH."
  >&2 echo "Please install VAST or configure and build with '--build-dir=$(git rev-parse --show-toplevel)/build'."
  exit 1
fi

# Create a temporary directory.
>&2 echo "Creating a temporary working directory"
demo_directory="$(mktemp -d)"
pushd "${demo_directory}"

# Download demo data.
>&2 echo "Downloading demo data"
curl -fSsl --progress-bar -o 'vast-jupyter-demo.tgz' \
  'https://storage.googleapis.com/tenzir-public-data/vast-jupyter-demo.tgz'
tar xzf 'vast-jupyter-demo.tgz'

# Start VAST node.
>&2 echo "Starting VAST node"
vast --db-directory=demo.db start &
while ! lsof -i ':42000'; do sleep 1; done

# Import demo data.
>&2 echo "Importing demo data"
vast import -b -r 'vast-jupyter-demo/M57-day11-18-conn.log' zeek
vast import -b -r 'vast-jupyter-demo/M57-day11-18.json' suricata
vast import -b -r 'vast-jupyter-demo/M57-2009-day11-18.trace' pcap

# Setup virtual environment.
>&2 echo "Setting up virtual environment"
pushd "${repository}/examples/jupyter"
python3 -m venv venv
source venv/bin/activate
python -m pip install wheel
python -m pip install -r 'requirements.txt'
pushd "${repository}/pyvast"
python setup.py install
popd
ipython kernel install --user --name=venv

# Run notebook.
>&2 echo "Running Jupyter Notebook (quit Notebook to shut down properly)"
jupyter notebook "${@:-}" || true
popd

# Stop VAST.
>&2 echo "Stopping VAST node"
vast stop

# Remove the temporary directory.
>&2 echo "Removing working directory"
popd
rm -rf "${demo_directory}"
