#!/bin/bash
SELF=$(readlink -f "$0")
HERE=${SELF%/*}
export PATH="${HERE}/usr/bin:${HERE}/bin:${PATH}"

# Locate available port
PORT=5173
while lsof -i :$PORT >/dev/null 2>&1; do
    PORT=$((PORT+1))
done

cd "${HERE}/usr/share/drcoder"
PORT=$PORT NODE_ENV=production node server/index.js &
PID=$!
trap "kill $PID 2>/dev/null" EXIT

sleep 1
if which xdg-open >/dev/null 2>&1; then
    xdg-open "http://127.0.0.1:$PORT"
elif which google-chrome >/dev/null 2>&1; then
    google-chrome --app="http://127.0.0.1:$PORT"
elif which chromium-browser >/dev/null 2>&1; then
    chromium-browser --app="http://127.0.0.1:$PORT"
fi

wait $PID
