defmodule Mix.Tasks.Compile.Proto do
  use Mix.Task.Compiler

  @manifest "compile.proto"

  @impl true
  def run(_args) do
    output = "./lib/prymn_proto"
    sources = Path.wildcard("../proto/*.proto")
    targets = Path.wildcard(output <> "/*.pb.ex")

    if Mix.Utils.stale?(sources, targets) do
      {_, 0} = do_protoc(sources, output)
    end

    :ok
  end

  @impl true
  def manifests(), do: [manifest()]
  defp manifest(), do: Path.join(Mix.Project.manifest_path(), @manifest)

  defp do_protoc(sources, output) do
    System.cmd(
      "protoc",
      [
        "--elixir_out=plugins=grpc:" <> output,
        "--elixir_opt=package_prefix=prymn_proto",
        "-I",
        "../proto"
      ] ++ sources
    )
  end
end