#!/bin/bash
# Start the BCT website (safe to run any time: does nothing if it is already running).
source "$(dirname "$(readlink -f "$0")")/_common.sh"

if [ -n "$(site_pids)" ] && [ "$(http_code)" = "200" ]; then
  echo "Already running (PID $(site_pids | tr '\n' ' ')) on port $PORT."; exit 0
fi

echo "Starting BCT website on port $PORT with $PY ..."
MARK="=== start.sh $(date '+%Y-%m-%d %H:%M:%S') ==="; echo "$MARK" >> "$LOG"
nohup "$PY" app.py >> "$LOG" 2>&1 < /dev/null &
echo $! > "$PIDFILE"

show_log() { awk -v m="$MARK" '$0==m{f=1;next} f' "$LOG" | tail -25; }

for i in $(seq 1 30); do
  sleep 1
  if ! kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
    echo "FAILED: the app stopped right away. Last lines of $LOG:"; show_log; exit 1
  fi
  if [ "$(http_code)" = "200" ]; then
    echo "OK: running (PID $(cat "$PIDFILE")), http://127.0.0.1:$PORT/ answers 200 after ${i}s."; exit 0
  fi
done
echo "WARNING: process $(cat "$PIDFILE") is running but the site did not answer within 30s. Last lines of $LOG:"
show_log; exit 1
