defmodule CvGen.Watchdog do use GenServer require Logger @name __MODULE__ @paths CvGen.paths() def start_link(_), do: GenServer.start(__MODULE__, [], name: @name) def force_reload(), do: GenServer.call(@name, :reload, 500) @impl true def init(_), do: {:ok, %{tpl_hash: "", json_hash: ""}, {:continue, :trigger_timer}} @impl true def handle_info(:timer_expired, state) do state = with tpl_hash <- hash(@paths.template), json_hash <- hash(@paths.data) do if tpl_hash != state.tpl_hash or json_hash != state.json_hash do Logger.info("Content has changed, reloading") CvGen.generate() %{tpl_hash: tpl_hash, json_hash: json_hash} else state end end {:noreply, state, {:continue, :trigger_timer}} end defp hash(path) do contents = File.read!(path) :crypto.hash(:md5, contents) |> Base.encode16() end @impl true def handle_call(:reload, _, _) do CvGen.generate() {:reply, :ok, %{tpl_hash: hash(@paths.template), json_hash: hash(@paths.data)}, {:continue, :trigger_timer}} end @impl true def handle_continue(:trigger_timer, state) do Process.send_after(self(), :timer_expired, 100) {:noreply, state} end end