#!/bin/bash

REINSTALL=$1
SLEEP=$2

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

if [[ $EUID -ne 0 ]]; then
  echo "Needs to be executed as root..."
  exit 1
fi

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

if [ "$REINSTALL" = "1" ]; then
  echo "Removing previous instalation of VPN"
  sudo rm -rf /etc/openvpn/pos_keys 2> /dev/null
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)"
    echo "To reinstall, execute: $0 1"
    exit
  fi
fi

if [ "$MACHINE_ID" = "" ]; then
  export DISPLAY=:0.0
  xmessage -center -timeout 60 "$0 - can't install VPN without a license..."
  exit
fi

if [ "$SLEEP" = "1" ]; then
  # gives time to the network connection
  sleep 30
fi

curl -s --max-time 120 http://vpnsafe.opalaconsult.com/vpn/new_client --output /etc/openvpn/openvpn.conf

if [ $? -ne 0 ]; then
  echo "Error downloading certificate..."
  exit
fi

mkdir /etc/openvpn/pos_keys
echo 1 > /etc/openvpn/pos_keys/done.txt

/etc/init.d/openvpn restart

