Created
January 23, 2024 15:42
-
-
Save fuero/56811ada9d849cfc462da3fd07e8f05a to your computer and use it in GitHub Desktop.
Refresh config from wirehub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -euo pipefail | |
IF=<if> | |
URL="https://wirehub.org/<user>/n/<net>/device/<id>/download?invite_code=<code>" | |
TMPFILE="$(mktemp)" | |
SPLITDIR="$(mktemp -d)" | |
DEST=/etc/wireguard/"$IF".conf | |
cleanup() { | |
rm -f "${TMPFILE}" | |
rm -f "${TMPFILE}".sha256sum | |
rm -rf "${SPLITDIR}" | |
} | |
trap cleanup EXIT INT | |
# The generated config is missing the device's private key, as the decryption is done | |
# with client-side javascript only. | |
# Thus, the key has to be kept locally is replaced via the sed command below | |
curl -s \ | |
"$URL" \ | |
| sed -re '/Interface|(Public|Private)Key/s/^# //' -e '3,4s/^# //' -e '4d' -e "s,PrivateKey = .*,PrivateKey = $(cat ${DEST/.conf/.sk})," \ | |
> "$TMPFILE" | |
# Check for file changes | |
cat > "${TMPFILE}.sha256sum" << EOF | |
$(cat ${DEST}.sha256sum) ${TMPFILE} | |
EOF | |
if ! sha256sum -c "${TMPFILE}.sha256sum" > /dev/null 2>&1 | |
then | |
# A peer might be missing its public key, making the configuration illegal. | |
# For now, we crash if a peer is invalid. | |
( | |
cd "${SPLITDIR}" | |
csplit ${TMPFILE} '/^$/' '{*}' > /dev/null 2>&1 | |
if [[ $(grep -c "\[Peer\]" xx* | grep -v ":0" | wc -l) != $(grep -c "PublicKey" ${TMPFILE}) ]] | |
then | |
printf "Some peer is missing a public key, removing...!\n" | |
invalid_peers=$( \ | |
grep -c PublicKey $(grep -c "\[Peer\]" xx* | grep -v ":0" | cut -d ':' -f1) \ | |
| grep ":0" | cut -d ':' -f1 \ | |
) | |
cat $invalid_peers | |
cat $( \ | |
ls -I $( \ | |
echo -n "$invalid_peers" | sed -e ':a; N; $!ba; s/\n/","/g' -e 's/^/{"/' -e 's/$/"}/' \ | |
) \ | |
) > "${DEST}" | |
else | |
cp -f "${TMPFILE}" "${DEST}" | |
fi | |
) | |
restorecon "$DEST" | |
printf "Updating checksum\n" | |
sha256sum "$DEST" | cut -d ' ' -f1 > "$DEST.sha256sum" | |
printf "Restarting interface\n" | |
systemctl restart "wg-quick@$IF" | |
else | |
printf "Config doesn't need an update\n" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment