class Dps8m < Formula
  desc "Simulator of the 36-bit GE/Honeywell/Bull 600/6000-series mainframe computers"
  homepage "https://dps8m.gitlab.io/"
  url "https://dps8m.gitlab.io/dps8m-r3.1.0-archive/R3.1.0/dps8m-r3.1.0-src.tar.gz"
  sha256 "4f09cb3e0106f39864617f17f3858e15cca1e9588fd50dde9bc736808f89e26b"
  license "ICU"
  head "https://gitlab.com/dps8m/dps8m.git", branch: "master"

  livecheck do
    url "https://dps8m.gitlab.io/dps8m/Releases/"
    regex(/href=.*?dps8m[._-]r?(\d+(?:\.\d+)+)[._-]src\.t/i)
  end

  no_autobump! because: :requires_manual_review

  depends_on "lld" => :build
  depends_on "llvm" => :build
  depends_on "libuv"

  uses_from_macos "bash"

  def install
    if OS.mac? && MacOS.version < :sonoma
      system "make"
    else
      # Upstream issue: https://gitlab.com/dps8m/dps8m/-/issues/293
      inreplace "src/pgo/Build.PGO.Homebrew.Clang.sh", "exit 1", ""
      inreplace "src/pgo/Build.PGO.Homebrew.Clang.sh", "$(brew --prefix llvm)", "$BREW_LLVM_PATH"
      ENV["BREW_LLVM_PATH"] = Formula["llvm"].opt_prefix
      ENV["NO_PGO_LIBUV"] = "1"
      ENV.append "LDFLAGS", "-Wl,-rpath,\"#{Formula["libuv"].opt_lib}\" -L\"#{Formula["libuv"].opt_lib}\" -luv"
      ENV.append "CFLAGS", "-I\"#{Formula["libuv"].opt_include}\""
      system "./src/pgo/Build.PGO.Homebrew.Clang.sh", "LIBUV="
    end
    system "make", "install", "PREFIX=#{prefix}"
  end

  test do
    require "expect"
    require "pty"
    timeout = 10
    PTY.spawn(bin/"dps8", "-t") do |r, w, pid|
      refute_nil r.expect("sim>", timeout), "Expected sim>"
      w.write "SH VE\r"
      refute_nil r.expect("Version:", timeout), "Expected Version:"
      w.write "q\r"
      refute_nil r.expect("Goodbye", timeout), "Expected Goodbye"
    ensure
      r.close
      w.close
      Process.wait(pid)
    end
  end
end
