#!/bin/bash

if [ ! -d "/etc/openvpn" ]; then
  echo "Can't find /etc/openvpn, aborting..."
  exit
fi

HAS_NETWORK=`/opt/pos/common/bin/has_network`
MACHINE_ID=`/opt/pos/common/bin/machine_id`

if [ "$HAS_NETWORK" = "NO" ]; then
  echo "Network connection not available, aborting..."
  exit
fi

if [ -d "/etc/openvpn/pos_keys" ]; then
  HAS_FILES=`ls /etc/openvpn/pos_keys`

  if [ "$HAS_FILES" != "" ]; then
    VPN_IP=`ip -4 -o addr show dev tun0 | awk '{split($4,a,"/");print a[1]}'`
    echo "VPN certificate installed already, aborting... ($VPN_IP)"
    exit
  fi
fi

echo "Will download a VPN certificate..."
wget -o /dev/null -q -O cert.zip "http://vpn.ptcert.com:10300/vpn/get_certificate?description=$MACHINE_ID"

if [ "$?" != "0" ]; then
  echo "There was a problem downloading VPN certificate..."
  exit
fi

rm -rf ca.crt client.crt client.key
tar zxf cert.zip
rm -rf cert.zip
mkdir -p /etc/openvpn/pos_keys
mv ca.crt client.crt client.key /etc/openvpn/pos_keys
rm -rf /etc/openvpn/*.conf

echo "client
dev tun
proto udp
remote vpn.ptcert.com 11194
resolv-retry infinite
nobind
persist-key
persist-tun
keepalive 10 120
ca pos_keys/ca.crt
cert pos_keys/client.crt
key pos_keys/client.key
comp-lzo
verb 3
" > /etc/openvpn/openvpn.conf

/etc/init.d/openvpn restart

systemctl daemon-reload 2> /dev/null
service openvpn start 2> /dev/null

