{ config, pkgs, hyper, secrets, ... }:
let dns-user = "cloudflare"; in
{
  sops.secrets = {
    # "nx2site/namecheap.pw" = { };
    # "nx2site/cloudflare/api-token-dns-edit" = { };
    "nx2site/cloudflare/global-api-key" = { 
      owner = dns-user;
    };
  };

  users = {
    users = {
      "${dns-user}" = {
        isSystemUser = true;
        group = dns-user;
      };
      "${hyper.user}".extraGroups = [ dns-user ];
    };
    groups."${dns-user}" = {};
  };

  systemd = {
    timers."dynamic-dns" = {
      wantedBy = [ "timers.target" ];
      timerConfig = {
        OnBootSec = "1m";
        OnUnitActiveSec = "10m";
        Unit = "dynamic-dns.service";
      };
    };
    services."dynamic-dns" = {
      script = let 
        dyn-dns = let
          account_id = secrets.email.gmail-online.mail;
          zone_id = "33fecab36e060f49d492127345ea95a0";
          record_id = { # curl --request GET --url https://api.cloudflare.com/client/v4/zones/33fecab36e060f49d492127345ea95a0/dns_records --header 'Content-Type: application/json' --header 'X-Auth-Email: <hidden>@gmail.com' --header "X-Auth-Key: <hiddenreadinsops>" -s | jq
            base  = "58d3412e8d88889d1a611b3669f0700f";
            base6 = "d1b90e21d2d747dcb30448bd65312927";
            sub   = "fc861353142bc05d5dbad1799178e6a1";
            sub6  = "b8082b7afe9e80971fc9f9dda16ec284";
            ssh   = "c0f14f17f32d6595c202f041dd836eb3";
            ssh6  = "f1ecb2d9d0522d4eec06437688ca76da";
            dev   = "80e76834acc9243696d9763759b22147";
          };
          passord-file-path = config.sops.secrets."nx2site/cloudflare/global-api-key".path;
        in pkgs.writers.writePython3Bin "dyn_dns" {
      libraries = with pkgs.python3Packages; [ requests ];
      flakeIgnore = [ "E302" "E305" "E226" "E501" "E261" ];
    } /* python */ ''
import requests
import subprocess
from time import sleep

def get_public_ip(ipv6: bool = False) -> str:
    return subprocess.run(['${pkgs.curl}/bin/curl', '-s', '-6' if ipv6 else '-4', 'https://ifconfig.me'], capture_output=True, text=True).stdout.strip()

def update_record(record_id: str, record_name: str, ip: str, type: str, proxied: bool, pw: str) -> None:
    sleep(5)
    return requests.patch(
        f'https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/{record_id}',
        headers={
            'Content-Type': 'application/json',
            'X-Auth-Email': '${account_id}',
            'X-Auth-Key': pw
        },
        json={
            "comment": "Domain verification record",
            "name": record_name,
            "proxied": proxied,
            "settings": {},
            "tags": [],
            "ttl": 1, # automatic
            "content": ip,
            "type": type
        }
    )

def main():
    my_ip = get_public_ip()
    my_ip6 = get_public_ip(ipv6=True)

    with open("${passord-file-path}", 'r') as pw_file:
        pw = pw_file.read().strip()

    # Perform DNS updates
    # https://developers.cloudflare.com/api/operations/dns-records-for-a-zone-update-dns-record
    print(f"${hyper.domain}: {update_record(record_id="${record_id.base}", record_name="${hyper.domain}", ip=my_ip, type="A", proxied=True, pw=pw).status_code}", end=", ")
    print(f"*.${hyper.domain}: {update_record(record_id="${record_id.sub}", record_name="*.${hyper.domain}", ip=my_ip, type="A", proxied=True, pw=pw).status_code}", end=", ")
    print(f"ssh.${hyper.domain}: {update_record(record_id="${record_id.ssh}", record_name="ssh.${hyper.domain}", ip=my_ip, type="A", proxied=False, pw=pw).status_code}", end=", ")
    print(f"dev.${hyper.domain}: {update_record(record_id="${record_id.dev}", record_name="dev.${hyper.domain}", ip=my_ip, type="A", proxied=False, pw=pw).status_code}", end=", ")

    print(f"${hyper.domain}: {update_record(record_id="${record_id.base6}", record_name="${hyper.domain}", ip=my_ip6, type="AAAA", proxied=True, pw=pw).status_code}", end=", ")
    print(f"*.${hyper.domain}: {update_record(record_id="${record_id.sub6}", record_name="*.${hyper.domain}", ip=my_ip6, type="AAAA", proxied=True, pw=pw).status_code}", end=", ")
    print(f"ssh.${hyper.domain}: {update_record(record_id="${record_id.ssh6}", record_name="ssh.${hyper.domain}", ip=my_ip6, type="AAAA", proxied=False, pw=pw).status_code}", end="")

if __name__ == "__main__":
    main()
      ''; in /* bash */ ''
        set -e
        ${dyn-dns}/bin/dyn_dns 
      '';
      serviceConfig = {
        Type = "oneshot";
        User = dns-user;
      };
    };
  };
  # networking.hosts = { # docker network inspect nx2site_default | grep -E "Name|IPv4" | tr "\n" " " | sed -r 's- +- -g;s-\n?"Name": -\n-g' | sed -r '1d;2d;s-"(.+?)", "IPv4Address": "(.+)/16",-  "\2" = [ "\1.docker" ];-g'
    # "172.1.2.1" = [ "staticweb.docker" ]; 
    # "172.1.3.1" = [ "matrix.docker" ]; 
    # "172.1.0.9" = [ "matrixdb.docker" ]; 
    # "172.1.4.1" = [ "matrix-ss.docker" ]; 
    # "172.1.0.7" = [ "matrix-ssdb.docker" ]; 
    # "172.1.5.1" = [ "pw.docker" ]; 
    # "172.1.6.1" = [ "git.docker" ]; 
    # "172.1.0.10" = [ "gitdb.docker" ];
    # "172.1.7.1" = [ "nn.docker" ]; 
    # "172.1.8.1" = [ "llm.docker" ]; 
    # "172.1.9.1" = [ "proxy.docker" ]; 
    # "172.1.10.1" = [ "share.docker" ]; 
    # "172.1.11.1" = [ "odq.docker" ]; 
  # };
}
