1alias Plausible.{Auth.User, Repo, Sites}
2
3# Provision the first owner before the public registration page can be served.
4endpoint = Application.fetch_env!(:plausible, PlausibleWeb.Endpoint)
5Application.put_env(:plausible, PlausibleWeb.Endpoint, Keyword.put(endpoint, :server, false))
6oban = Application.fetch_env!(:plausible, Oban)
7Application.put_env(:plausible, Oban, Keyword.merge(oban, queues: [], plugins: [], peer: false))
8{:ok, _} = Application.ensure_all_started(:plausible)
9
10{:ok, _} =
11 Repo.transaction(fn ->
12 email = System.fetch_env!("ADMIN_EMAIL")
13
14 user =
15 Repo.get_by(User, email: email) ||
16 if Repo.exists?(User) do
17 raise "Owner email does not match the existing installation"
18 else
19 password = System.fetch_env!("INITIAL_ADMIN_PASSWORD")
20
21 case Repo.insert(
22 User.new(%{
23 email: email,
24 name: "Clover",
25 password: password,
26 password_confirmation: password
27 })
28 ) do
29 {:ok, user} -> user
30 {:error, _} -> raise "Could not create the Plausible owner"
31 end
32 end
33
34 domain = System.fetch_env!("SITE_DOMAIN")
35
36 site =
37 if site = Sites.get_by_domain(domain) do
38 unless Sites.get_for_user(user, domain, roles: [:owner]) do
39 raise "The configured owner does not own this site"
40 end
41
42 site
43 else
44 {:ok, %{site: site}} =
45 Sites.create(user, %{domain: domain, timezone: System.fetch_env!("SITE_TIMEZONE")})
46
47 site
48 end
49
50 PlausibleWeb.Tracker.get_or_create_tracker_script_configuration!(site, %{
51 installation_type: :manual,
52 outbound_links: true
53 })
54 end)