class Opal::CliRunners::Firefox

def run_firefox_server

def run_firefox_server
  raise 'Firefox server can be started only on localhost' if chrome_host != DEFAULT_CHROME_HOST
  profile = mktmpprofile
  # For options see https://github.com/puppeteer/puppeteer/blob/main/packages/puppeteer-core/src/node/FirefoxLauncher.ts
  firefox_server_cmd = %{#{OS.shellescape(firefox_executable)} \
    --no-remote \
    --profile #{profile} \
    --headless \
    --remote-debugging-port #{chrome_port} \
    #{ENV['FIREFOX_OPTS']}}
  firefox_pid = Process.spawn(firefox_server_cmd, in: OS.dev_null, out: OS.dev_null, err: OS.dev_null)
  Timeout.timeout(30) do
    loop do
      break if firefox_server_running?
      sleep 0.5
    end
  end
  yield
rescue Timeout::Error
  puts 'Failed to start firefox server'
  puts 'Make sure that you have it installed and that its version is > 100'
  exit(1)
ensure
  if OS.windows? && firefox_pid
    Process.kill('KILL', firefox_pid) unless system("taskkill /f /t /pid #{firefox_pid} >NUL 2>NUL")
  elsif firefox_pid
    Process.kill('HUP', firefox_pid)
  end
  FileUtils.rm_rf(profile) if profile
end