cfg/bin/gen-syncthing-cert
2025-12-30 13:54:59 +01:00

44 lines
No EOL
1.2 KiB
Bash
Executable file

#!/bin/sh
set -euo pipefail
tmp=$(mktemp -d)
trap 'rm -rf -- "$tmp"' EXIT
FILEPATH="${MANAGED_CLIENTS:-./var/syncthing-managed-clients.json}"
PKI_PATH="${PKI_PATH:-./pki/syncthing}"
SECRETS_PATH="${SECRETS_PATH:-secrets/syncthing}"
first_missing=$(
jq -r '
. as $root
| $root.managed_clients[]
| select($root.hashes[.] | not)
' $FILEPATH \
| head -n 1 \
)
[ -z "$first_missing" ] && echo "Done" >&2 && exit 0
echo "Generating cerificate for $first_missing"
mkdir $tmp/$first_missing
hash=$(
syncthing generate \
--config $tmp/$first_missing \
--data $tmp/$first_missing/data \
| grep -oP '(?<=device=)[A-Z0-9-]+' \
)
mkdir -p $PKI_PATH
mv $tmp/$first_missing/cert.pem $PKI_PATH/$first_missing.cert
# Remove the file so agenix does not try to decrypt
[ -f "$SECRETS_PATH/$first_missing.age" ] && rm "$SECRETS_PATH/$first_missing.age"
agenix -e $SECRETS_PATH/$first_missing.age < $tmp/$first_missing/key.pem
jq --arg client "$first_missing" \
--arg hash "$hash" \
'.hashes[$client] = $hash' "$FILEPATH" \
> "$tmp/new-syncthing-managed-clients.json" \
&& mv "$tmp/new-syncthing-managed-clients.json" "$FILEPATH"
# Revoke self to handle next client
"$0"