class Seal < Formula
  desc "Easy-to-use homomorphic encryption library"
  homepage "https://github.com/microsoft/SEAL"
  url "https://github.com/microsoft/SEAL/archive/v3.6.0.tar.gz"
  sha256 "7751b57c0c66c1e81bb25cdddeaca6340e4475e11ab04faa27f3e0dc7526c236"
  license "MIT"

  bottle do
    sha256 "ce0fb24c40e48c23d4dc49f4b5ee6224e29569764aaa4294cf43d57cd1573e6d" => :big_sur
    sha256 "2ca03d844ddb12e68af1a8ad95114915620bd6106225b6937a952ab5eb369694" => :catalina
    sha256 "fd7e10b8cadce6c8eb1ab5cdba2de6165dffeef247d2361296c6e0f03dcafea4" => :mojave
    sha256 "0b81d1c3ac1a57d7302c83f5bde56ebab2142f1fddc04a0b94ff9ae531c7116a" => :x86_64_linux
  end

  depends_on "cmake" => [:build, :test]

  # #pragma GCC error "SEAL requires __GNUC__ >= 6"
  # In reality gcc@6 does not work because of some missing C++17 features.
  unless OS.mac?
    fails_with gcc: "5"
    fails_with gcc: "6"
    fails_with gcc: "7"
    depends_on "gcc@8" => [:build, :test]
  end

  def install
    system "cmake", "-DBUILD_SHARED_LIBS=ON", ".", *std_cmake_args
    system "make"
    system "make", "install"
    pkgshare.install "native/examples"
  end

  test do
    ENV["CXX"] = Formula["gcc@8"].opt_bin/"g++-8" unless OS.mac?
    cp_r (pkgshare/"examples"), testpath

    # remove the partial CMakeLists
    File.delete testpath/"examples/CMakeLists.txt"

    # Chip in a new "CMakeLists.txt" for example code tests
    (testpath/"examples/CMakeLists.txt").write <<~EOS
      cmake_minimum_required(VERSION 3.12)
      project(SEALExamples VERSION #{version} LANGUAGES CXX)
      # Executable will be in ../bin
      set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SEALExamples_SOURCE_DIR}/../bin)

      add_executable(sealexamples examples.cpp)
      target_sources(sealexamples
          PRIVATE
              1_bfv_basics.cpp
              2_encoders.cpp
              3_levels.cpp
              4_ckks_basics.cpp
              5_rotation.cpp
              6_serialization.cpp
              7_performance.cpp
      )

      # Import Microsoft SEAL
      find_package(SEAL #{version} EXACT REQUIRED
          # Providing a path so this can be built without installing Microsoft SEAL
          PATHS ${SEALExamples_SOURCE_DIR}/../src/cmake
      )

      # Link Microsoft SEAL
      target_link_libraries(sealexamples SEAL::seal_shared)
    EOS

    system "cmake", "examples"
    system "make"
    # test examples 1-5 and exit
    input = "1\n2\n3\n4\n5\n0\n"
    assert_match "Correct", pipe_output("bin/sealexamples", input)
  end
end
