freyanet/inet2.initd

109 lines
2.8 KiB
Text
Raw Normal View History

2023-11-11 00:44:48 +00:00
#!/sbin/openrc-run
name="inet2"
description="Sets up wireguard interfaces connected via the host's internet connection"
extra_started_commands="reloadwg"
run() {
printf '$ \x1b[32;1m%s\x1b[0m\n' "$*"
"$@"
}
step() {
printf '\x1b[34;1m>> %s\x1b[0m\n' "$*"
}
getval() {
/usr/local/bin/config.awk /run/inet2/inet2.conf "$@"
}
runscripts() {
if [ -n "$(getval "interface $2" "$1")" ]; then
step "Running $1 for $2"
getval "interface $2" "$1" | while read -r line; do
(eval "$line")
done
fi
}
start() {
rm -rf /run/inet2/config 2>/dev/null
rm -rf /run/inet2/wg 2>/dev/null
cp /config/inet2.conf /run/inet2/inet2.conf
mkdir /run/inet2/wg
getval Loopback | while read -r addr; do
run ip addr add "$addr" dev lo
done
getval interface | while read -r inter; do
step "Generating config for $inter"
run mkwgconfig.sh "$inter" /run/inet2/wg/"$inter"
# create the wireguard interface *in the default namespace*
step "Adding Wireguard interface $inter"
run ip link add name "$inter" type wireguard
# set up the new network from the config
step "Setting Wireguard config for $inter"
run wg setconf "$inter" /run/inet2/wg/"$inter"
# the config doesn't actually add any addresses, do that here
step "Adding host addresses for $inter"
getval "interface $inter" Address | while read -r addr; do
run ip addr add "$addr" dev "$inter"
done
runscripts PreUp "$inter"
step "Bringing interface up"
run ip link set dev "$inter" up
getval "interface $inter" Route | while read -r line; do
read -r route via addr2 < <(printf "%s" "$line")
if [ "$via" = "via" ]; then
run ip route add "$route" via "$addr2" dev "$inter"
else
run ip route add "$route" dev "$inter"
fi
done
runscripts PostUp "$inter"
done
step "Done!"
}
stop() {
if [ -f /run/inet2/inet2.conf ]; then
getval Loopback | while read -r addr; do
run ip addr del "$addr" dev lo
done
getval interface | while read -r inter; do
runscripts PreDown "$inter"
step "Bringing $inter down"
run ip link del "$inter"
runscripts PostDown "$inter"
done
rm -rf /run/inet2/inet2.conf
fi
}
# just reloads the wireguard configs for existing interfaces
# for if a peer's domain name resolves to a different ip address now
# and it needs to be re-resolved without taking down the connection
reloadwg() {
if [ -f /run/inet2/inet2.conf ]; then
getval interface | while read -r inter; do
step "Generating config for $inter"
run mkwgconfig.sh "$inter" /run/inet2/wg/"$inter" /config/inet2.conf
step "Setting Wireguard config for $inter"
run wg setconf "$inter" /run/inet2/wg/"$inter"
done
fi
}