#!/usr/bin/env bash
# 20260305 ChatGPT
# $Header$
#
# Copy/paste examples:
#   
#   ./viewglb model.glb

FILE="$1"

if [ -z "$FILE" ]; then
    echo "Usage: $0 /path/to/file.glb" >&2
    exit 1
fi

if [ ! -f "$FILE" ]; then
    echo "ERROR: file not found: $FILE" >&2
    exit 1
fi

DIR=$(dirname "$FILE")
BASE=$(basename "$FILE")
VIEWER="__glbviewer__.html"
LOG="/tmp/viewglb_httpserver.log"

urlencode() {
    python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1]))' "$1"
}

find_free_port() {
    python3 - <<'PY'
import socket
s = socket.socket()
s.bind(('127.0.0.1', 0))
print(s.getsockname()[1])
s.close()
PY
}

PORT=$(find_free_port)
BASE_URL=$(urlencode "$BASE")

cd "$DIR" || exit 1

cat >"$VIEWER" <<EOF
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>$BASE</title>
</head>
<body style="margin:0;background:#222;overflow:hidden;">

<div style="
  position:absolute;
  bottom:10px;
  left:50%;
  transform:translateX(-50%);
  z-index:10;
  padding:6px 12px;
  background:rgba(0,0,0,0.65);
  color:#fff;
  font-family:monospace;
  font-size:14px;
  border-radius:4px;
  max-width:80vw;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
">$BASE</div>

<script type="module" src="https://unpkg.com/@google/model-viewer/dist/model-viewer.min.js"></script>

<model-viewer src="$BASE_URL"
              camera-controls
              auto-rotate
              style="width:100vw;height:100vh;">
</model-viewer>

</body>
</html>
EOF

python3 -m http.server "$PORT" >"$LOG" 2>&1 &
SERVER=$!

# wait up to ~5 seconds for server readiness
READY=0
for _i in 1 2 3 4 5 6 7 8 9 10; do
    if ! kill -0 "$SERVER" 2>/dev/null; then
        echo "ERROR: http.server exited early." >&2
        echo "See log: $LOG" >&2
        rm -f "$VIEWER"
        exit 1
    fi

    if curl -s "http://127.0.0.1:$PORT/$VIEWER" >/dev/null 2>&1; then
        READY=1
        break
    fi

    sleep 0.5
done

if [ "$READY" -ne 1 ]; then
    echo "ERROR: server did not become ready on port $PORT" >&2
    echo "See log: $LOG" >&2
    kill "$SERVER" 2>/dev/null
    rm -f "$VIEWER"
    exit 1
fi

firefox-bin "http://127.0.0.1:$PORT/$VIEWER" >/dev/null 2>&1 &

read -p "Press Enter to stop server..."

kill "$SERVER" 2>/dev/null
rm -f "$VIEWER"
