#!/bin/bash
# Start Phoenix + Livebook together. Livebook attaches to the Phoenix node
# and gets full access to Repo, Scorer, Weather, etc.
#
# Usage: bin/notebook
# Then open http://localhost:8081

set -e

COOKIE="microwaveprop_nb"
NODE="prop@$(hostname -s)"
PORT="${LIVEBOOK_PORT:-8081}"

# Find livebook: PATH, then mix escripts dir
LIVEBOOK="$(command -v livebook 2>/dev/null || echo "$(elixir -e 'IO.write(Path.join(Mix.path_for(:escripts), "livebook"))')")"
if [ ! -x "$LIVEBOOK" ]; then
  echo "Livebook not found. Install with: mix escript.install hex livebook"
  exit 1
fi

echo "Starting Phoenix on :4000 and Livebook on :${PORT}..."
echo "Livebook will be at http://localhost:${PORT}"
echo ""

# Start Phoenix in background with a node name
elixir --sname prop --cookie "$COOKIE" -S mix phx.server &
PHOENIX_PID=$!

# Wait for the node to come up
sleep 3

# Start Livebook attached to the Phoenix node
# LIVEBOOK_APPS_PATH makes notebooks show up under "Apps" on the home page
LIVEBOOK_HOME="$(pwd)/notebooks" \
LIVEBOOK_APPS_PATH="$(pwd)/notebooks" \
LIVEBOOK_APPS_PATH_HUB_ID="personal-hub" \
  "$LIVEBOOK" server \
  --port "$PORT" \
  --default-runtime "attached:${NODE}:${COOKIE}" &
LIVEBOOK_PID=$!

# Trap ctrl-c to kill both
trap "kill $PHOENIX_PID $LIVEBOOK_PID 2>/dev/null; exit" INT TERM

echo "Phoenix PID: $PHOENIX_PID, Livebook PID: $LIVEBOOK_PID"
echo "Press Ctrl-C to stop both."

wait
