{ config, lib, pkgs, ... }: let cfg = config.cloudflare-dns; in { options.cloudflare-dns = { enable = lib.mkEnableOption "Cloudflare DNS management via flarectl"; apiToken = lib.mkOption { type = lib.types.str; description = "Cloudflare API token"; }; zoneId = lib.mkOption { type = lib.types.str; description = "Cloudflare zone ID (from your domain's Cloudflare page)"; }; records = lib.mkOption { type = lib.types.listOf ( lib.types.submodule { options = { name = lib.mkOption { type = lib.types.str; description = "DNS record name (e.g., 'uptime' for uptime.example.com)"; }; type = lib.mkOption { type = lib.types.str; default = "A"; description = "DNS record type (A, AAAA, CNAME, etc.)"; }; content = lib.mkOption { type = lib.types.str; description = "DNS record content (IP address, hostname, etc.)"; }; proxied = lib.mkOption { type = lib.types.bool; default = true; description = "Use Cloudflare proxy (orange cloud)"; }; ttl = lib.mkOption { type = lib.types.int; default = 1; description = "TTL (1 = auto)"; }; }; } ); default = [ ]; description = "List of DNS records to manage"; }; }; config = lib.mkIf cfg.enable { environment.systemPackages = [ pkgs.flarectl ]; systemd.services.cloudflare-dns-update = { description = "Update Cloudflare DNS records"; wantedBy = [ "multi-user.target" ]; serviceConfig = { Type = "oneshot"; Environment = [ "CF_API_TOKEN=${cfg.apiToken}" ]; }; script = '' ${lib.concatMapStringsSep "\n" (record: '' echo "Updating DNS record: ${record.name} (${record.type}) -> ${record.content}" ${pkgs.flarectl}/bin/flarectl \ --zone ${cfg.zoneId} \ add \ --name ${record.name} \ --type ${record.type} \ --content ${record.content} \ --proxied ${toString record.proxied} \ --ttl ${toString record.ttl} || \ ${pkgs.flarectl}/bin/flarectl \ --zone ${cfg.zoneId} \ update \ --id $(${pkgs.flarectl}/bin/flarectl --zone ${cfg.zoneId} --name ${record.name} --type ${record.type} | grep -oP '(?<=ID:\s)\S+' | head -1) \ --content ${record.content} \ --proxied ${toString record.proxied} \ --ttl ${toString record.ttl} '') cfg.records} ''; }; }; }