#!/bin/bash
# JJ UH-VPN setup script for Network Manager
if [ "$(id -u)" = 0 ]; then
  echo "Don't run this script as root please." 1>&2
  exit 1
fi

cat << EOF
This script sets up UH-VPN for you assuming you have Linux, Network Manager
and network-manager-openvpn packages installed.

Last updated by Jani Jaakkola 2021-11-18.
EOF

umask 022

# Check that network-manager-openvpn-gnome is installed.
if test -x /usr/bin/dpkg && 
  ! dpkg -s network-manager-openvpn-gnome > /dev/null 2>&1
then
  echo "You need to install network-manager-openvpn-gnome first."
  command="sudo apt-get install network-manager-openvpn-gnome"
  echo "Now running: $command"
  if ! $command; then
    echo "Sorry, install failed. Try again."
    exit 1
  fi
fi
  

# Save certificate to somewhere.
CA="$HOME/.hy-vpn-ca-2020.pem"
cat << EOF > $CA
-----BEGIN CERTIFICATE-----
[payload removed: 2100 characters in 33 lines]
-----END CERTIFICATE-----
EOF

read -e -i "$USER" -p "Your Univ. Helsinki user account: " HYUSER

tun="uh-vpn-helsinkifi-only ($HYUSER)"
if ! nmcli c show "$tun" >/dev/null 2>&1; then
  nmcli c add \
    con-name "$tun" \
    ifname "*" \
    type vpn \
    connection.permissions user:$USER \
    ipv4.method auto \
    ipv4.routes "128.214.0.0/16 10.113.100.29" \
    ipv4.ignore-auto-routes yes \
    ipv4.never-default true \
    ipv4.dns-priority -25 \
    vpn.service-type org.freedesktop.NetworkManager.openvpn \
    vpn.data "$(cat << EOF
dev-type = tun, \
connection-type = password, \
username = $HYUSER, \
password-flags = 1, \
remote = hy-vpn.vpn.helsinki.fi, \
ca = $HOME/.hy-vpn-ca-2020.pem, \
remote-cert-tls = server, \
comp-lzo = yes, \
cipher = AES-256-GCM, \
auth = SHA512
EOF
)"
fi

# uh-vpn-allroute
tun="uh-vpn-allroute ($HYUSER)"
if ! nmcli c show "$tun" >/dev/null 2>&1; then
  nmcli c add \
  con-name "$tun" \
  ifname "*" \
  type vpn \
  connection.permissions user:$USER \
  ipv4.method auto \
  ipv4.ignore-auto-routes no \
  ipv4.dns-priority -25 \
  vpn.service-type org.freedesktop.NetworkManager.openvpn \
  vpn.data "$(cat << EOF
dev-type = tun, \
connection-type = password, \
username = $HYUSER, \
password-flags = 1, \
remote = hy-vpn.vpn.helsinki.fi, \
ca = $HOME/.hy-vpn-ca-2020.pem, \
remote-cert-tls = server, \
comp-lzo = yes, \
cipher = AES-256-GCM, \
auth = SHA512
EOF
)"
fi
