#!/bin/zsh
# Start Tukodinge (if it is not already running) and open it in the browser.
#   tukoding         start and open
#   tukoding stop    stop the server
#   tukoding backup  copy your record to Documents and, if plugged in, the backup drive
APP="${0:A:h}"          # the folder this script really lives in, even when started through a link
PORT="${TUKODINGE_PORT:-5200}"
running() { lsof -ti tcp:$PORT -sTCP:LISTEN >/dev/null 2>&1; }

if [[ "$1" == "ship" ]]; then
  shift
  exec "$APP/tools/ship.sh" "$@"
fi

if [[ "$1" == "backup" ]]; then
  cd "$APP" && python3 server.py --backup
  exit $?
fi

if [[ "$1" == "stop" ]]; then
  if running; then kill $(lsof -ti tcp:$PORT -sTCP:LISTEN) && echo "Tukodinge stopped."; else echo "Tukodinge is not running."; fi
  exit 0
fi

if running; then
  echo "Tukodinge is already running."
else
  cd "$APP" || { echo "Cannot find $APP"; exit 1; }
  nohup python3 server.py > "$APP/data/server.log" 2>&1 &
  for i in 1 2 3 4 5 6 7 8 9 10; do running && break; sleep 0.3; done
  running && echo "Tukodinge started." || { echo "Tukodinge did not start. See $APP/data/server.log"; exit 1; }
fi
open "http://localhost:$PORT"
