#!/bin/bash

dl_url='download.sigsolucoes.net.br/public/vpn-clientes/'

case $1 in
  sigerp)
    name='sigerp-cloud'
    profile='sigerp.app.ovpn'
  ;;
  clientes)
    name='sig-cliente'
    profile='clientes.sigsolucoes.net.br.ovpn'
  ;;
  local|*)
    name='sigerp'
    profile='ovpn-sigerp.ovpn'
  ;;
esac

suite=$(lsb_release -cs)

apt-get update \
&& apt-get -y install \
  ca-certificates \
  curl \
  openssl

rm -f /etc/apt/trusted.gpg.d/openvpn*.gpg
curl -fsSL https://swupdate.openvpn.net/repos/repo-public.gpg \
  | gpg --dearmor \
  > /etc/apt/trusted.gpg.d/openvpn-repo-public.gpg

rm -f /etc/apt/sources.list.d/openvpn*.list
echo "deb [arch=amd64] https://build.openvpn.net/debian/openvpn/stable ${suite} main" \
  > /etc/apt/sources.list.d/openvpn-aptrepo.list

apt-get update \
&& apt-get -y install \
  openvpn \
  tmate \
&& cd /etc/openvpn/client \
&& (mv ../${name}.* . > /dev/null 2>&1 || true) \
&& curl -fsSL https://${dl_url}/${profile} -o ${name}.conf \
&& chown daemon:daemon ${name}.conf ${name}.passwd \
&& systemctl disable openvpn.service \
&& systemctl enable openvpn-client@${name}.service \
&& systemctl restart openvpn-client@${name}.service \
&& echo "net.ipv4.tcp_window_scaling=1" > /etc/sysctl.d/50-openvpn.conf \
&& cd -

case $suite in
  xenial)
    cd /etc/openvpn \
    && rm -rf *.conf > /dev/null 2>&1 \
    && curl -fsSL https://${dl_url}/${profile} -o ${name}.conf \
    && chown daemon:daemon ${name}.conf ${name}.passwd \
    && systemctl disable openvpn.service \
    && systemctl enable openvpn@${name}.service \
    && systemctl restart openvpn@${name}.service \
    && echo "net.ipv4.tcp_window_scaling=0" > /etc/sysctl.d/50-openvpn.conf \
    && cd -
  ;;
esac

exit $?
