89 lines
2.7 KiB
Nix
89 lines
2.7 KiB
Nix
{ 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 check‐script 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 last‐seen 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";
|
||
};
|
||
};
|
||
}
|