Files
cloonar-assistant/modules/cloonar-assistant/updns/default.nix
2025-04-29 10:21:58 +02:00

89 lines
2.7 KiB
Nix
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{ config, pkgs, lib, ... }: {
### 1) Make sure we have the tools we need
environment.systemPackages = with pkgs; [
curl
jq
];
sops.secrets.updns-client = {
owner = "updns-client";
restartUnits = [ "updns-client.service" ];
};
### 3) Write the checkscript into /etc/external-ip/check.sh (0400, executable)
environment.etc."updns-client/run.sh".text = lib.mkIf config.cloonar-assistant.updns-client.enable ''
#!/usr/bin/env bash
set -euo pipefail
# Where our secret lives (encrypted)
SECRET=${config.cloonar-assistant.updns-client.secretFile}
# Where we record the lastseen IP
LAST_IP_FILE=/var/lib/updns-client/last-ip
# Decrypt the API key at runtime
API_KEY=$(cat "$SECRET")
# Fetch current external IP
IP=$(curl -fsSL https://ifconfig.me)
# Ensure state directory exists
mkdir -p "$(dirname \"$LAST_IP_FILE\")"
# Read old IP (if any)
if [[ -f "$LAST_IP_FILE" ]]; then
OLD_IP=$(< "$LAST_IP_FILE")
else
OLD_IP=""
fi
# If it's changed, notify the API and update the file
if [[ "$IP" != "$OLD_IP" ]]; then
PAYLOAD=$(jq -n \
--arg key \"${config.cloonar-assistant.updns-client.key}" \
--arg secret "$SECRET" \
--arg host "${config.cloonar-assistant.domain}" \
--arg ip "$IP" \
'{key: $key, secret: $secret, host: $host, ip: $ip}')
curl -fsS -X POST https://updns-client.cloonar.com/update \
-H "Content-Type: application/json" \
-d "$PAYLOAD"
echo "$IP" > "$LAST_IP_FILE"
fi
'';
environment.etc."updns-client/run.sh".mode = "0500";
### 4) Ensure /var/lib/external-ip exists on boot
systemd.tmpfiles.rules = [
# path mode owner group age
"d /var/lib/updns-client 0755 root root -"
];
### 5) Define the oneshot service
systemd.services.updns-client = lib.mkIf config.cloonar-assistant.updns-client.enable {
description = "Check external IP and notify API on change";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
Type = "oneshot";
WorkingDirectory = "/var/lib/updns-client";
ExecStart = "${pkgs.bash}/bin/bash /etc/updns-client/run.sh";
};
wantedBy = [ "multi-user.target" ];
};
### 6) Define the timer (runs at boot + every 5 minutes)
systemd.timers.updns-client = lib.mkIf config.cloonar-assistant.updns-client.enable {
description = "Run updns-client.service every 5 minutes";
wantedBy = [ "timers.target" ];
timerConfig = {
OnBootSec = "1min";
OnUnitActiveSec = "5min";
Persistent = true;
Unit = "updns-client.service";
};
};
}