#!/bin/bash

mkdir -p /config/cdm/devices/chrome_1610
mkdir -p /config/logs/
mkdir -p /config/chromium

if [ ! -f /config/config.conf ] && [ ! -f /config/config.json ]; then
  cp /default-config/config.conf /config/config.conf
fi

if [ ! -f /config/rules.json ]; then
  cp /default-config/rules.json /config/rules.json
fi

# Check if --cli flag was passed
if [[ " $@ " =~ " --cli " ]]; then
  # CLI mode - no need for X server
  # Remove --cli from arguments
  args=("$@")
  filtered_args=()
  for arg in "${args[@]}"; do
    if [ "$arg" != "--cli" ]; then
      filtered_args+=("$arg")
    fi
  done

  /app/cli/OF\ DL.Cli "${filtered_args[@]}"
else
  # GUI mode - start X server and window manager
  {
    supervisord -c /etc/supervisor/conf.d/supervisord.conf &
  } &> /dev/null

  # Wait for the 4 supervisor programs to start: X11 (Xvfb), openbox, X11vnc, and noVNC
  NUM_RUNNING_SERVICES=$(supervisorctl -c /etc/supervisor/conf.d/supervisord.conf status | grep RUNNING | wc -l)
  while [ $NUM_RUNNING_SERVICES != "4" ]; do
    sleep 1
    NUM_RUNNING_SERVICES=$(supervisorctl -c /etc/supervisor/conf.d/supervisord.conf status | grep RUNNING | wc -l)
  done

  # Wait for X server to be ready to accept connections
  echo "Waiting for X server to be ready..."
  timeout=30
  elapsed=0
  until xdpyinfo -display "$DISPLAY" >/dev/null 2>&1; do
    if [ $elapsed -ge $timeout ]; then
      echo "Timeout waiting for X server"
      exit 1
    fi
    sleep 1
    elapsed=$((elapsed + 1))
  done
  echo "X server is ready"

  /app/gui/OF\ DL.Gui "$@"
fi
