#!/bin/bash

# ----------------------------------------------
# Test an OpenVPN server setup with CA
# ----------------------------------------------

set -ex

CONFIG_DIR=/etc/openvpn
CA_DIR=easy-rsa
CA_VARS_FILE=vars
DEVICE=tun1
IP_NETWORK=10.9.8.0
NETWORK_MASK=255.255.255.0
LOG_FILE=$AUTOPKGTEST_TMP/openvpn.log

# Print information message to stdout
info() {
  echo "[I] $1"
}

info "Create the CA directory inside the config directory"
cd $CONFIG_DIR
make-cadir $CA_DIR
cd $CA_DIR

info \
"Add some variables to the $CA_VARS_FILE to build the CA and keys in a non interactive mode"
cat << EOF >> $CA_VARS_FILE
set_var EASYRSA_REQ_COUNTRY     "US"
set_var EASYRSA_REQ_PROVINCE    "California"
set_var EASYRSA_REQ_CITY        "San Francisco"
set_var EASYRSA_REQ_ORG "Copyleft Certificate Co"
set_var EASYRSA_REQ_EMAIL       "me@example.net"
set_var EASYRSA_REQ_OU          "My Organizational Unit"

set_var EASYRSA_BATCH           "1"
EOF

info "Setup the CA and the server keys"
./easyrsa --batch init-pki
# remove conflicting vars file to avoid easy-rsa errors
rm -f vars
./easyrsa --batch build-ca nopass 2>/dev/null
./easyrsa --batch build-server-full server nopass 2>/dev/null
./easyrsa --batch gen-dh 2>/dev/null

info "Create the OpenVPN server config file"
cat << EOF > /etc/openvpn/server.conf
dev $DEVICE
server $IP_NETWORK $NETWORK_MASK

ca      $CONFIG_DIR/$CA_DIR/pki/ca.crt
cert    $CONFIG_DIR/$CA_DIR/pki/issued/server.crt
key     $CONFIG_DIR/$CA_DIR/pki/private/server.key
dh      $CONFIG_DIR/$CA_DIR/pki/dh.pem
EOF

info "Start an OpenVPN process in background and redirect its output to a file"
openvpn --config $CONFIG_DIR/server.conf --verb 6 > $LOG_FILE &

info "Give some time to start the process, check if the TUN device is opened"
count=1
until [ -f $LOG_FILE ] && cat $LOG_FILE | grep "TUN/TAP device $DEVICE opened"; do
  [ $count -gt 9 ] && exit 5
  count=$(expr $count + 1)
  sleep 1
done

info "Check if the $DEVICE was created and if the state is UNKNOWN at this point"
ip address show $DEVICE | grep 'state UNKNOWN'

info "Check if OpenVPN is listening on port 1194 (default port)"
ss -lnptu | grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}:1194.*users:\(\(\"openvpn\"'

info "Check if Diffie-Hellman was initialized"
cat $LOG_FILE | grep 'Diffie-Hellman initialized'

info "Check if the $DEVICE is linked"
cat $LOG_FILE | grep "net_iface_up: set $DEVICE up"

info "Check if the network route was correctly configured"
cat $LOG_FILE | grep "net_route_v4_add: $IP_NETWORK/24 via"

info "Check if the Initialization Sequence completed"
cat $LOG_FILE | grep 'Initialization Sequence Completed'

# Clean up: kill tha OpenVPN process, remove the $DEVICE created and CA dir
cleanup() {
  pkill openvpn
  rm -rf $CONFIG_DIR/$CA_DIR
}
trap cleanup INT TERM EXIT
