docker-vpn/start-openvpn.sh
2022-03-24 01:32:10 +01:00

61 lines
1.3 KiB
Bash

#!/usr/bin/env bash
set -o pipefail
change_hostname() {
echo VPNDOCKER > /etc/hostname
}
create_net_dev() {
mkdir -p /dev/net
mknod /dev/net/tun c 10 200
chmod 600 /dev/net/tun
}
connect_vpn() {
sed -e 's|^up .*$|up /etc/openvpn/up.sh|' \
-e 's|^down .*$|down /etc/openvpn/down.sh|' \
-e 's|^auth-user-pass.*$|auth-user-pass|' \
"$OVPN_CONFIGURATION_FILE" > /tmp/ovpn.conf
openvpn --config /tmp/ovpn.conf --daemon
}
get_ip() {
nsout="$(nslookup -timeout=1 myip.opendns.com resolver1.opendns.com)"
if [ "$?" != 0 ]; then
echo "WARN: Failed to run nslookup" >&2
fi
echo "$nsout" | grep -o 'Address:.*' | grep -Eo '(\d+\.?){4}' | tail -n1
}
print_ip() {
echo "VPN IP: $(get_ip)"
}
switch_user() {
su -c "cd $OVPN_WORKDIR && "'$SHELL' -l "$OVPN_USER"
}
own_ip="$(get_ip)"
echo "OWN IP: $own_ip"
if [ "$own_ip" = "" ]; then
echo "ERROR: Failed to lookup own ip, aborting" >&2
exit 1
fi
change_hostname
create_net_dev
connect_vpn
for _ in {1..50}; do
vpn_ip="$(get_ip)"
if [ "$vpn_ip" = "$own_ip" ] || [ "$vpn_ip" = "" ]; then
sleep .1
else
break
fi
done
if [ "$vpn_ip" = "$own_ip" ] || [ "$vpn_ip" = "" ]; then
echo "ERROR: Failed to connect to VPN (vpn_ip=$vpn_ip), aborting" >&2
exit 1
fi
echo "VPN IP: $vpn_ip"
switch_user