#!/bin/sh
set -eu
APP_RES=$(CDPATH= cd -- "$(dirname -- "$0")/../Resources/BlogToBook" && pwd)
DATA="$HOME/Library/Application Support/BlogToBook"
ARTIFACTS="$HOME/Documents/BlogToBook"
mkdir -p "$DATA/images" "$ARTIFACTS"
if curl -fsS --max-time 1 http://127.0.0.1:4173/ >/dev/null 2>&1; then open http://localhost:4173/; exit 0; fi
BTB_DATA_DIR="$DATA" BTB_ARTIFACTS_DIR="$ARTIFACTS" "$APP_RES/node" "$APP_RES/server.mjs" &
PID=$!
cleanup(){ kill "$PID" 2>/dev/null || true; wait "$PID" 2>/dev/null || true; }
trap cleanup EXIT INT TERM
i=0
while [ "$i" -lt 50 ]; do
  if curl -fsS --max-time 1 http://127.0.0.1:4173/ >/dev/null 2>&1; then open http://localhost:4173/; wait "$PID"; exit 0; fi
  if ! kill -0 "$PID" 2>/dev/null; then echo 'BlogToBook could not start; port 4173 may be occupied.' >&2; exit 1; fi
  i=$((i+1)); sleep 0.2
done
echo 'Timed out waiting for BlogToBook.' >&2; exit 1
