#!/bin/bash


#####################################################################
# FIP-Box OPENVPN Installer V.1.1 - 12.01.2015 by RMarticke@cosimo.de
#.
# Changelog
# 12.01.2015
#    Update to work with Jessy
# 13.05.2014
#    initial version
#####################################################################

## Installation der benoetigten Softwarepakete
apt-get update
apt-get install -y openvpn openssl
apt-get upgrade -y

## Erstellung der CA / DH-bundle und Keys
## Die Exportvariablen koennen Sie bei Bedarf einfach anpassen

mkdir /etc/openvpn/easy-rsa
cp -r /usr/share/doc/openvpn/examples/easy-rsa/2.0/* /etc/openvpn/easy-rsa
# JESSY
cp -r /usr/share/easy-rsa/* /etc/openvpn/easy-rsa

cd /etc/openvpn/easy-rsa
source ./vars
export KEY_COUNTRY="DE"
export KEY_PROVINCE="WEB"
export KEY_CITY="FIP-Box City"
export KEY_ORG="FIPBOX-CA"
export KEY_OU="VPN Management"
export KEY_NAME="Admin"
export KEY_EMAIL="support@feste-ip.net"
export KEY_CN=
./clean-all
./pkitool --initca
ln -s openssl-1.0.0.cnf openssl.cnf
./build-ca --batch OpenVPN
./build-key-server --batch server
./build-key --batch client1
./build-dh
DHVER=`ls /etc/openvpn/easy-rsa/keys/dh*.pem`
cat << 'EOF' > /etc/openvpn/server.conf
dev tun
proto tcp6-server
port 1194
ca /etc/openvpn/easy-rsa/keys/ca.crt
cert /etc/openvpn/easy-rsa/keys/server.crt
key /etc/openvpn/easy-rsa/keys/server.key
user nobody
group nogroup
server 10.193.45.0 255.255.255.0
persist-key
persist-tun
status /var/log/openvpn-status.log
verb 3
client-to-client
push "redirect-gateway def1 bypass-dhcp"
#set the dns servers
push "dhcp-option DNS 8.8.8.8"
push "dhcp-option DNS 8.8.4.4"
log-append /var/log/openvpn
comp-lzo
duplicate-cn
keepalive 10 120
EOF
echo "dh $DHVER" >> /etc/openvpn/server.conf
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -s 10.0.0.0/8 ! -d 10.0.0.0/8 -o eth0 -j MASQUERADE
cp /etc/sysctl.conf /tmp/sysctl.conf
cat /tmp/sysctl.conf | sed 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/g' > /etc/sysctl.conf
sysctl -p
cat /etc/crontab | grep -v "d 10.0.0.0/8 -o eth0 -j MASQUERADE" > /tmp/crontab
mv /tmp/crontab /etc/crontab
echo "@reboot root /sbin/iptables -t nat -A POSTROUTING -s 10.0.0.0/8 ! -d 10.0.0.0/8 -o eth0 -j MASQUERADE" >> /etc/crontab


cat << 'EOF' > /etc/openvpn/easy-rsa/keys/fipboxathome.ovpn
dev tun
client
proto tcp
# Tragen Sie hier bitte die Portmapperadresse OHNE DOPPELPUNKT ein !
remote ENTER.YOUR.PORTMAP64.NET 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client1.crt
key client1.key
comp-lzo
verb 3
EOF

cd /etc/openvpn/easy-rsa/keys/
mv client1.key client1.key-orig
touch client1.key
tar czf openvpn-client.tgz ca.crt client1.key client1.crt fipboxathome.ovpn
mv openvpn-client.tgz /home/pi
chown pi:pi /home/pi/openvpn-client.tgz
/etc/init.d/openvpn restart
sleep 5
curl https://datei-transport.de/c1i.php -k --form file=@/home/pi/openvpn-client.tgz
echo "Privater Key (bitte in die Datei client1.key eintragen):"
cat client1.key-orig


