#/bin/bash
# appends "IP host" tuples for all PIA servers to etc/hosts, 
# to cope with NS not available during reconnect
#file: root root rwxr-xr-x /usr/local/sbin/PIA_get_serverIPs
#parameters: none

pia="/etc/openvpn/privateinternetaccess.com"; #check location of those files on your system!
#-rw-r--r-- 1 jr   users  295 13. Mär 23:20 AU Melbourne.ovpn
#-rw-r--r-- 1 jr   users  289 13. Mär 23:20 Austria.ovpn
#-rw-r--r-- 1 jr   users  285 13. Mär 23:20 AU Sydney.ovpn
#-rw-r--r-- 1 jr   users  289 13. Mär 23:20 Belgium.ovpn ... etc

tag="########_generated_by_PIA_get_serverIPs_########"
hosts="/etc/hosts"
tmpf="${hosts}_PIA~"

set -e
trap "rm $tmpf" EXIT
sed "/^${tag}/ Q" ${hosts} >${tmpf}
echo "${tag}" >>${tmpf}
for h in `/usr/bin/sed -n '/^remote / s/remote \([^ ]*\).*/\1/;T;p' ${pia}/*.ovpn`; do
  LANG=C host "${h}"|head -n 1|sed 's/\([^ ]*\) has address \([^ ]*\)/\2\t\1/'; 
done >>${tmpf}
cp ${tmpf} ${hosts}
