#!/usr/bin/env ruby
# frozen_string_literal: true

require "bundler/setup"
require "webrick"

ALLOWED_ARGS = %w[-u --build]
EXTRA_ARGS = ARGV - ALLOWED_ARGS

if ARGV.include?("-h") || ARGV.include?("--help")
  puts <<~MSG
    bin/ember-cli is deprecated. Use bin/dev instead.

    Usage (backwards-compatible):
      bin/ember-cli           Runs `bin/dev --only ember` (frontend bundler only)
      bin/ember-cli -u        Runs `bin/dev` (Rails + frontend bundler)
      bin/ember-cli --build   Runs `pnpm build` (one-off frontend build, no watching)
  MSG
  exit 0
end

abort <<~MSG if !EXTRA_ARGS.empty?
    bin/ember-cli no longer accepts arguments: #{EXTRA_ARGS.join(" ")}

    Discourse now runs from a single port via `bin/dev`. Please switch to:
      bin/dev

    bin/ember-cli is retained only for backwards compatibility and supports:
      bin/ember-cli           (equivalent to `bin/dev --only ember`)
      bin/ember-cli -u        (equivalent to `bin/dev`)
      bin/ember-cli --build   (equivalent to `pnpm build`)
  MSG

child_command, display_command, run_stub_server =
  if ARGV.include?("--build")
    [%w[pnpm build], "pnpm build", false]
  elsif ARGV.include?("-u")
    [[File.expand_path("dev", __dir__)], "bin/dev", true]
  else
    [[File.expand_path("dev", __dir__), "--only", "ember"], "bin/dev --only ember", true]
  end

warn "\e[31m[bin/ember-cli] DEPRECATED: please use `#{display_command}` instead...\e[0m"

stub_port = (ENV["EMBER_CLI_STUB_PORT"] || 4200).to_i
target_port = ENV["UNICORN_PORT"] || "3000"

stub_message = <<~MSG
  <!doctype html>
  <html>
    <head>
      <title>Ember CLI Removed</title>
      <style>
        body { font-family: system-ui, sans-serif; max-width: 36rem; margin: 4rem auto; padding: 0 1rem; color: #222; line-height: 1.5; }
        h1 { font-size: 1.25rem; margin-bottom: 1rem; }
        code { background: #f3f3f3; padding: 0.1rem 0.35rem; border-radius: 3px; font-size: 0.95em; }
        a { color: #08c; }
      </style>
    </head>
    <body>
      <h1>Ember CLI has been replaced with Rolldown</h1>
      <p>Discourse is now served from a single port in development. Visit <a href="http://localhost:#{target_port}">http://localhost:#{target_port}</a>.</p>
      <p>To start Rails and the Rolldown build in a single command, use <code>bin/dev</code>.</p>
      <p>To launch the standalone frontend bundler, use <code>bin/dev --only ember</code>.</p>
    </body>
  </html>
MSG

stub_server =
  if run_stub_server
    begin
      WEBrick::HTTPServer.new(
        Port: stub_port,
        BindAddress: "0.0.0.0",
        Logger: WEBrick::Log.new(File::NULL),
        AccessLog: [],
      )
    rescue Errno::EADDRINUSE
      warn "[bin/ember-cli] Port #{stub_port} already in use; skipping deprecation stub server."
      nil
    end
  end

if stub_server
  stub_server.mount_proc "/" do |_req, res|
    res.status = 410
    res["Content-Type"] = "text/html; charset=utf-8"
    res.body = stub_message
  end
  Thread.new { stub_server.start }
end

child_pid = spawn(*child_command)

# Children in the foreground process group already receive INT from the terminal;
# swallow it here so we can clean up the stub server.
trap("INT") {}

begin
  Process.wait(child_pid)
ensure
  stub_server&.shutdown
end

exit($?.exitstatus || 0)
