WGSERVERIFACE="wg_mullvad"
FILE="servers.conf"
# pick a random server from list of all available servers
IFS=',' read -ra SETTINGS <<< "$(sort --random-sort $FILE | head -n 1)"
if [ ${#SETTINGS[@]} -eq 3 ]; then
uci set network.$WGSERVERIFACE.description="${SETTINGS[0]}"
uci set network.$WGSERVERIFACE.endpoint_host="${SETTINGS[1]}"
uci set network.$WGSERVERIFACE.public_key="${SETTINGS[2]}"
uci commit network
reload_config
ifup $WGSERVERIFACE >/dev/null 2>&1;
else
echo "oops"
fi
and then run /usr/local/sbin/wg-server-randomizer.sh in cron?
shellcheck is a great utility for catching bash-isms, as well as common errors (like redirects and quoting). It’s available both as an executable for desktop systems, as well as on their website.
Have made a couple of other changes since I needed to change the value of options in an unnamed section, but it's all working now. Here's my final script:
#!/bin/sh
WGPEER="wireguard_mullvad"
WGINTERFACE="mullvad"
FILE="servers.conf"
# pick a random server
IN=`sed -n $(awk 'END {srand(); r=rand()*NR; if (r<NR) {sub(/\..*/,"",r); r++;}; print r}' $FILE)p $FILE`
IFS="," read DESCRIPTION HOST PUBKEY << EOF
${IN}
EOF
uci set network.@"$WGPEER"[0].description="$DESCRIPTION"
uci set network.@"$WGPEER"[0].endpoint_host="$HOST"
uci set network.@"$WGPEER"[0].public_key="$PUBKEY"
uci commit network
reload_config
ifup $WGINTERFACE &>/dev/null
JFTR: It's a bit overkill setting the config file and especially saving it every time you rotate the server. I'm certainly not a member of the "oh my god the flash memory will die" camp, but depending on how often you rotate and write your config you might actually introduce some wear.
But most of all, it's not necessary and quite inelegant. Wireguard can be told to connect an interface to a different server using
wg set <interface> peer <public key> endpoint "<host>:<port>"
after which it will resolve the host and connect to it immediately.