summaryrefslogtreecommitdiff
path: root/static/js/dns-wizard.js
blob: 2ee7162ab1b41b610d84de4b4440e3c1048c32b5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
(function () {
  const cfg = window.DNS;
  if (!cfg) return;

  const form = (obj) => {
    const body = new URLSearchParams(obj);
    return { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body };
  };
  const addRecord = (type, name, content, ttl) =>
    fetch("/dns", form({ type, name, content, ttl: String(ttl || 300) }));
  const setPrimary = (mac) => fetch("/profile/primary", form({ mac }));

  // The wizard seeds the basics: <user>.<zone> -> primary device, plus a starter
  // alias per device you can rename or delete later. The server replaces an
  // existing CNAME at a name, so re-running this is safe.
  const wiz = document.getElementById("dns-wizard");
  if (wiz) {
    wiz.addEventListener("click", async () => {
      wiz.disabled = true;
      wiz.textContent = "wiring things up…";
      const primary = cfg.devices.find((d) => d.mac === cfg.primaryMac) || cfg.devices[0];
      if (primary) await addRecord("CNAME", cfg.userDomain, primary.name, 300);
      let n = 1;
      for (const d of cfg.devices) {
        await addRecord("CNAME", "device-" + n + "." + cfg.userDomain, d.name, 300);
        n++;
      }
      location.reload();
    });
  }

  // Picking a primary updates the stored choice and repoints <user>.<zone> at it
  // in one go, all client-side.
  document.querySelectorAll(".set-primary").forEach((btn) => {
    btn.addEventListener("click", async (e) => {
      e.preventDefault();
      btn.disabled = true;
      await setPrimary(btn.dataset.mac);
      await addRecord("CNAME", cfg.userDomain, btn.dataset.name, 300);
      location.reload();
    });
  });
})();