#!/bin/bash
if [ ! `id -u` = 0 ] ; then
        echo "error: This script needs to be run using 'sudo SCRIPT' or in 'root terminal'" >&2
  echo "exiting now" >&2
  exit 1
fi
if `grep -r $'\r' /home/amnesia/Persistent/tov.ovpn >/dev/null`
then
  unset tovcfgperm
  tovcfgperm=`stat -c%a /home/amnesia/Persistent/tov.ovpn`
  tr -d $'\r' < /home/amnesia/Persistent/tov.ovpn >/tmp/tov.ovpn && mv /tmp/tov.ovpn /home/amnesia/Persistent/
  chmod "$tovcfgperm" /home/amnesia/Persistent/tov.ovpn
  unset tovcfgperm
fi
grep "net.ipv6.conf.all.disable_ipv6 = 1" /etc/sysctl.conf || echo net.ipv6.conf.all.disable_ipv6 = 1 >> /etc/sysctl.conf 
sysctl -p
unset vpnserver_ip
unset vpnserver_port
unset vpnserver_proto
vpnserver_ip=`cat /home/amnesia/Persistent/tov.ovpn | grep "^remote " | awk '{print $2}'`
if [[ -z "$vpnserver_ip" ]] ; then echo 'error: VPN server IP not found in tov.ovpn!' >&2; exit 1; fi
if ! [[ "$vpnserver_ip" =~ ^[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+$ ]] ; then echo "error: 'remote' appears not to be an IP address in tov.ovpn" >&2; exit 1; fi
vpnserver_port=`cat /home/amnesia/Persistent/tov.ovpn | grep "^remote " | awk '{print $3}'`
if [[ -z "$vpnserver_port" ]] 
then
  vpnserver_port=`cat /home/amnesia/Persistent/tov.ovpn | grep "^port " | awk '{print $2}'`
fi
if [[ -z "$vpnserver_port" ]] ; then echo 'error: VPN server port not found in tov.ovpn!' >&2; exit 1; fi
if ! [[ "$vpnserver_port" =~ ^[0-9]+$ ]] ; then echo "error: 'port' appears not to be an integer (number)e in tov.ovpn" >&2; exit 1; fi
vpnserver_proto=`cat /home/amnesia/Persistent/tov.ovpn | grep "^remote " | awk '{print $4}'`
if [[ -z "$vpnserver_proto" ]] 
then
  vpnserver_proto=`cat /home/amnesia/Persistent/tov.ovpn | grep "^proto " | awk '{print $2}'`
fi
if [[ -z "$vpnserver_proto" ]] ; then echo 'info: VPN server protocol not found in tov.ovpn, using UDP' >&2; vpnserver_proto=udp; fi
if [ ! -f /usr/sbin/openvpn ]
then
  apt-cache search openvpn 2>/dev/nul | grep "openvpn - virtual private network daemon" || apt-get update
  apt-get install -y openvpn
fi
if [[ ! $(cat /etc/ferm/ferm.conf | grep "White-list access to Openvpnserver:port for user root") ]]
then
  awk '/White-list access to local resources/{print "            # White-list access to Openvpnserver:port for user root" RS "            daddr '$vpnserver_ip' proto udp dport 40138 {" RS "                    mod owner uid-owner root ACCEPT;" RS "            }"  RS RS $0;next}1' /etc/ferm/ferm.conf >/tmp/ferm.conf && mv /tmp/ferm.conf /etc/ferm
fi
if [[ ! $(cat /etc/ferm/ferm.conf | grep "# But only when using tun0.") ]]
then
   awk '/mod owner uid-owner debian-tor ACCEPT;/{print "            # But only when using tun0." RS "            outerface tun0 mod owner uid-owner debian-tor ACCEPT;";next}1' /etc/ferm/ferm.conf >/tmp/ferm.conf && mv /tmp/ferm.conf /etc/ferm
fi
rm -f /var/cache/ferm/*
echo nameserver 10.8.0.1 > /etc/resolv-over-clearnet.conf
/etc/init.d/ferm reload
openvpn --config /home/amnesia/Persistent/tov.ovpn