#!/bin/sh
#
# General start/stop script:
# - Set the correct name and path below
# - Set USAGE_STRING below and check the allowed states in the case block
# - adjust check_config to fail or copy a config file if it is missing
# - finally adjust everything if really necessary...
#
SERVICE_NAME="openvpn"
BINARY_FILE_NAME=openvpn
BINARY_FILE_PATH="/usr/sbin"
CONFIG_FILE_NAME=server.conf
CONFIG_FILE_PATH="/etc/openvpn"
LOOKUP_FILE_PATH="/opt/userdata/etc/sda"
PRE_START_SCRIPT="/opt/userdata/etc/openvpn/iptables_start.sh"
POST_STOP_SCRIPT="/opt/userdata/etc/openvpn/iptables_stop.sh"

EASYRSA_BIN=/usr/bin/easyrsa
IPTABLES_BIN=/usr/sbin/iptables

# if service check is true, start is only possible, if the enable file is present
# remember to activate allowed states enable / disable
CHECK_SERVICE_ENABLED=true
# The allowed services for the usage message. Eg. "start|stop|restart|enable|disable|status"
# restart_on_failure is only used internally, if the IscWebService is configured properly.
# network refresh will update the iptables rules and should be called if the network configuration has changed
USAGE_STRING="start|stop|restart|reload|enable [BRIDGED] [REDIRECT]|disable|status|restart_on_failure|configure [BRIDGED] [REDIRECT]|network_refresh|dhcp_renew|show_config"

#########################################################################################################
#                                                                                                       #
# ATTENTION: IF THE VPN CONFIGURATION WILL BE CHANGED WITHIN THIS SCRIPT CHANGE THE VERSION BELOW!!!    #
#                                                                                                       #
# E.g. the cipher changes from AES256GCM to another one in a next release.                              #
#                                                                                                       #
#########################################################################################################
VPNVERSION_CONTENT="20230511"

#### user parameter
export EASYRSA=/etc/openvpn/easy-rsa
SERVICE_MANUFACTURER=$(ls /opt/extparam/service*.crt | cut -d _ -f 2 | cut -d - -f 1)
SERVICE_SERIAL=$(ls /opt/extparam/service*.crt | cut -d _ -f 2 | cut -d - -f 2)
export EASYRSA_REQ_CN="${SERVICE_MANUFACTURER}-${SERVICE_SERIAL}"
export EASYRSA_REQ_COUNTRY=""
export EASYRSA_REQ_PROVINCE=""
export EASYRSA_REQ_ORG="Gira S1"
export EASYRSA_REQ_OU=""
export EASYRSA_REQ_EMAIL=""
export EASYRSA_CERT_EXPIRE=3650
export EASYRSA_CRL_DAYS=3650

# detect IP change, assume true per default
IP_CHANGED=1
IFACE=br0       

CURRENT_IP=$(ip addr show ${IFACE} | grep "inet " | cut -d "/" -f 0 | sed "s/ //g" | sed "s/inet//")
if [ -f /var/run/openvpn_ipcheck ]; then
	if [ "$(cat /var/run/openvpn_ipcheck)" != "${CURRENT_IP}" ]; then
		echo ${CURRENT_IP} > /var/run/openvpn_ipcheck
	else
		IP_CHANGED=0
	fi
else
	echo ${CURRENT_IP} > /var/run/openvpn_ipcheck
fi

user_post_start() {
	# Enable net.ipv4.ip_forward for the system
	echo 1 > /proc/sys/net/ipv4/ip_forward
	# flush NAT table
	${IPTABLES_BIN} -t nat -F
	# enable default ise table
	/etc/init.d/S18iptables restart
	# Autodetect IP address
	# Set NAT for the VPN subnet
	if ${IPTABLES_BIN} -L -n | grep -qE '^(REJECT|DROP)'; then
		# If iptables has at least one REJECT rule, we asume this is needed.
		# Not the best approach but I can't think of other and this shouldn't
		# cause problems.
		${IPTABLES_BIN} -I INPUT -p tcp --dport 1194 -j ACCEPT
		if [ ! -f ${BRIDGED_SERVICE} ]; then
			${IPTABLES_BIN} -I FORWARD -s 10.8.0.0/24 -j ACCEPT
		fi
		${IPTABLES_BIN} -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
	fi
	if [ ! -f ${BRIDGED_SERVICE} ]; then
		${IPTABLES_BIN} -t nat -A POSTROUTING -s 10.8.0.0/24 ! -d 10.8.0.0/24 -j SNAT --to ${CURRENT_IP}
		${IPTABLES_BIN} -t nat -I POSTROUTING -s 10.8.0.1 -p udp --sport 3671 -o tun0 -j SNAT --to-source ${CURRENT_IP}
		${IPTABLES_BIN} -t nat -I PREROUTING -i tun0 -d ${CURRENT_IP} -p udp --dport 3671 -j DNAT --to 10.8.0.1
	fi
}

user_post_stop() {
	# remove connection log, so the SdaService did not state possible open connections
	rm -f /var/log/openvpn-status.log
	# Disable net.ipv4.ip_forward for the system
	echo 0 > /proc/sys/net/ipv4/ip_forward
	# enable default ise table
	${IPTABLES_BIN} -t nat -F
	/etc/init.d/S18iptables restart
}

bin2dec()
{
        echo $1 | awk 'func b(i, t,a,c){a=1;for(c=length(i);c>0;c--){t+=substr(i,c,1)=="1"?a:0;a*=2}return t}{printf "%d",b($1)}'
}

ip2net()
{
        ip=$1
        cdr=$2
        oldIFS=${IFS}
        local IFS
        IFS=.
        set -- $ip
        i1=$1
        i2=$2
        i3=$3
        i4=$4
        
        IFS=${oldIFS}
        mask=""
        for a in $(seq 1 32); do
          if [ $(((a - 1) % 8)) -eq 0 ]; then 
            mask=${mask}.;
          fi
          if [ $a -le $cdr ]; then 
            mask=${mask}1; 
          else 
            mask=${mask}0; 
          fi; 
        done
        IFS=.
        set -- $mask
        m1=$(bin2dec $2)
        m2=$(bin2dec $3)
        m3=$(bin2dec $4)
        m4=$(bin2dec $5)
        
        printf "%d.%d.%d.%d\n" "$((i1 & $m1))" "$((i2 & $m2))" "$((i3 & $m3))" "$((i4 & $m4))"
}

cdr2mask()
{
        set -- $(( 5 - ($1 / 8) )) 255 255 255 255 $(( (255 << (8 - ($1 % 8))) & 255 )) 0 0 0
        [ $1 -gt 1 ] && shift $1 || shift
        echo ${1-0}.${2-0}.${3-0}.${4-0}
}

generate_server_config() {
    # generate a new server configuration
    if [ -f ${BRIDGED_SERVICE} ]; then
        generate_server_bridged_config
    else
        generate_server_default_config
    fi
}
generate_server_default_config() {
# Generate server.conf
	echo "port 1194
proto tcp
dev tun
sndbuf 0
rcvbuf 0
management localhost 7505
management-client-pf
management-client-auth
auth-user-pass-optional
ca ca.crt
cert server.crt
key server.key
dh dh.pem
auth SHA512
tls-auth ta.key 0
topology subnet
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt" > /etc/openvpn/server.conf
        if [ ! -z "${VPN_REDIRECT}" -a "${VPN_REDIRECT}" == "REDIRECT" ]; then
                echo 'push "redirect-gateway def1 bypass-dhcp"' >> /etc/openvpn/server.conf
                log_std "Redirect gateway and bypass DHCP."
        else
                # get ip and set route
                cdr=$(ip addr show ${IFACE} | grep "inet " | sed "s/^ *//" | cut -d " " -f 2 | cut -d"/" -f 2)
                ip=$(ip addr show ${IFACE} | grep "inet " | sed "s/^ *//" | cut -d " " -f 2 | cut -d"/" -f 1)
                netmask=$(cdr2mask ${cdr})
                route=$(ip2net ${ip} ${cdr})
                echo 'push "route '${route} ${netmask}'"' >> /etc/openvpn/server.conf
                log_std "Only route corresponding traffic to VPN subnet."
        fi
        # DNS
        RESOLVCONF='/etc/resolv.conf'
        # Obtain the resolvers from resolv.conf and use them for OpenVPN
        grep -v '#' $RESOLVCONF | grep 'nameserver' | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | while read line; do
                echo "push \"dhcp-option DNS $line\"" >> /etc/openvpn/server.conf
        done
        echo "keepalive 10 120
cipher AES-256-GCM
user nobody
group nogroup
persist-key
persist-tun
status /var/log/openvpn-status.log
verb 2
crl-verify crl.pem" >> /etc/openvpn/server.conf
}

generate_server_bridged_config() {
# Generate server.conf
	echo "port 1194
proto tcp
dev tap0
sndbuf 0
rcvbuf 0
management localhost 7505
management-client-pf
management-client-auth
auth-user-pass-optional
ca ca.crt
cert server.crt
key server.key
dh dh.pem
auth SHA512
tls-auth ta.key 0" > /etc/openvpn/server.conf
# get ip and set route

ip=$(ip addr show ${IFACE} | grep "inet " | sed "s/^ *//" | cut -d " " -f 2 | cut -d"/" -f 1)
cdr=$(ip addr show ${IFACE} | grep "inet " | sed "s/^ *//" | cut -d " " -f 2 | cut -d"/" -f 2)
ippool="${ip%.*}.200 ${ip%.*}.210"
netmask=$(cdr2mask ${cdr})
route=$(ip2net ${ip} ${cdr})
gateway=$(ip route | grep ${IFACE} | grep default | cut -d" " -f3)
echo "server-bridge" >> /etc/openvpn/server.conf
        if [ ! -z "${VPN_REDIRECT}" -a "${VPN_REDIRECT}" == "REDIRECT" ]; then
                echo 'push "redirect-gateway def1 bypass-dhcp"' >> /etc/openvpn/server.conf
                log_std "Redirect gateway and bypass DHCP."
        else
		echo 'push "route-gateway '${gateway}'"' >> /etc/openvpn/server.conf
                echo 'push "route '${route} ${netmask}'"' >> /etc/openvpn/server.conf
                log_std "Only route corresponding traffic to VPN subnet."
        fi
# DNS
RESOLVCONF='/etc/resolv.conf'
# Obtain the resolvers from resolv.conf and use them for OpenVPN
grep -v '#' $RESOLVCONF | grep 'nameserver' | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | while read line; do
echo "push \"dhcp-option DNS $line\"" >> /etc/openvpn/server.conf
done
echo "keepalive 10 120
cipher AES-256-GCM
user nobody
group nogroup
persist-key
persist-tun
status /var/log/openvpn-status.log
verb 2
crl-verify crl.pem" >> /etc/openvpn/server.conf
}

generate_client_common() {
        # client-common.txt as template to add users
        echo "client" > /etc/openvpn/client-common.txt
if [ -f ${BRIDGED_SERVICE} ]; then
  echo "dev tap" >> /etc/openvpn/client-common.txt
else 
  echo "dev tun" >> /etc/openvpn/client-common.txt
fi
echo "proto tcp
sndbuf 0
rcvbuf 0
remote {{ConnectorID}} 1194 tcp
http-proxy vpnproxy.{{Host}} 80
http-proxy-option AGENT {{ConnectorID}}:{{Key}}
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
auth SHA512
cipher AES-256-GCM
setenv opt block-outside-dns
key-direction 1
verb 3" >> /etc/openvpn/client-common.txt
}

user_enable_script() {
        if [ -f ${SERVICE_ENABLED} ]; then
            # already configured, call generate_server_config in case the configuration has been changed
            generate_server_config
          exit 0
        fi
	# OpenVPN setup
	# Autodetect IP address
	IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1)
	# create KIM file structure
	rm -rf /opt/userdata/etc/openvpn
	mkdir -p /opt/userdata/etc/openvpn/clientprofiles
	# -----  
	# add a vpnconfig.version file with the content of VPNVERSION_CONTENT
	# If the file exists and the cointent differs, we assume a deprecated
	# configuration, see "show_config" below.
	echo ${VPNVERSION_CONTENT} > /etc/openvpn/vpnconfig.version
	# -----
	cp -r /etc/easy-rsa /opt/userdata/etc/openvpn
	cd /etc/openvpn/easy-rsa
	# Create the PKI, set up the CA and the server and client certificates
	${EASYRSA_BIN} init-pki
	# workaround for missing .rnd file in /etc/openvpn/easy-rsa/pki
	if [ ! -f /etc/openvpn/easy-rsa/pki/.rnd ]; then
		dd if=/dev/urandom of=/etc/openvpn/easy-rsa/pki/.rnd bs=256 count=4
	fi
	# enable TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384 for TLS connections
	${EASYRSA_BIN} --vars=/etc/easy-rsa/vars --curve=secp521r1 --use-algo=ec --batch build-ca nopass
	export -n EASYRSA_REQ_CN
	${EASYRSA_BIN} --vars=/etc/easy-rsa/vars --curve=secp521r1 --use-algo=ec --batch build-server-full server nopass
	${EASYRSA_BIN} --vars=/etc/easy-rsa/vars gen-crl
	# Move the stuff we need
	cp pki/ca.crt pki/private/ca.key pki/issued/server.crt pki/private/server.key pki/crl.pem /etc/openvpn
	# CRL is read with each client connection, when OpenVPN is dropped to nobody
	chown nobody:nogroup /etc/openvpn/crl.pem
	# Generate key for tls-auth
	${BINARY_FILE_PATH}/${BINARY_FILE_NAME} --genkey secret /etc/openvpn/ta.key
	# Create the DH parameters file using the predefined ffdhe2048 group
	echo '-----BEGIN DH PARAMETERS-----
MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz
+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a
87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7
YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi
7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD
ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg==
-----END DH PARAMETERS-----' > /etc/openvpn/dh.pem
	# generate configurations
  generate_server_config
  generate_client_common
}

user_disable_script() {
	# remove openvpn configuration    
	rm -rf /etc/openvpn/*
	# Disable net.ipv4.ip_forward for the system
	echo 0 > /proc/sys/net/ipv4/ip_forward
	# enable default ise table
	/etc/init.d/S18iptables restart
}


#### general parameter

CONFIG_FILE="${CONFIG_FILE_PATH}/${CONFIG_FILE_NAME}"
BINARY_FILE="${BINARY_FILE_PATH}/${BINARY_FILE_NAME}"
SERVICE_ENABLED="/opt/userdata/.${SERVICE_NAME}-enabled"
BRIDGED_SERVICE="/opt/userdata/.${SERVICE_NAME}-bridged"
PID_FILE="/var/run/${SERVICE_NAME}.server.pid"
SERVICE_STARTED="/opt/userdata/.${SERVICE_NAME}-started"

START_PARAMETER="--daemon --writepid ${PID_FILE} --config $CONFIG_FILE_PATH/$CONFIG_FILE_NAME --cd $CONFIG_FILE_PATH --log-append /var/log/openvpn.log"

log() {
	if [ "$(type logger)" != "" ]; then
		logger -t "${SERVICE_NAME}" "$1"
	else
		echo "$1"
	fi
}

log_std() {
	if [ "$(type logger)" != "" ]; then
		logger -t "${SERVICE_NAME}" "$1"
		echo "$1"
	else
		echo "$1"
	fi
}

# Check that the service exists.
if [ ! -f ${BINARY_FILE} ]; then
	log "Service not installed!"
	log_std "failure"
	exit 1
fi

check_config() {
	# if directory is missing, create it... the next test will fail.
	# check config directory
	if [ -d "${CONFIG_FILE_PATH}" ]; then
		log "${CONFIG_FILE_PATH} found."
	else
		log "${CONFIG_FILE_PATH} not found."
		log "Creating ${CONFIG_FILE_PATH}."
		mkdir -p "${CONFIG_FILE_PATH}"
	fi
	# check for valid configuration file; fail if not present
	if [ ! -f ${CONFIG_FILE} ]; then
		log "Configfile ${CONFIG_FILE} not found - can not start the service!"
		log_std "failure"
		exit 1
	fi
	log "Configfile ${CONFIG_FILE} found."
	# regenerate if not up to date
	if [ "$IP_CHANGED" == "1" ]; then
		log "IP changed to ${CURRENT_IP} updating ${CONFIG_FILE}."
		generate_server_config
	fi
}

start() {
	# be sure the lookup folder for the SdaService exists
	mkdir -p ${LOOKUP_FILE_PATH}
	log "Try to start service ${SERVICE_NAME}."
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		if [ ! -f ${SERVICE_ENABLED} ]; then
			log "Service is disabled!"
			log_std "failure"
			exit 1
		fi
	fi
	configure_network
	check_config
	if [ "$(pidof ${SERVICE_NAME})" != "" ]; then
		log "Try stop previous ${SERVICE_NAME}."
		stop
	fi
	log "Starting ${SERVICE_NAME}"
	${BINARY_FILE} ${START_PARAMETER}
	RETVAL=$?
	pidof ${BINARY_FILE_NAME} > ${PID_FILE}
	if [ "$?" != "0" ]; then
		log_std "failed"
		return $RETVAL
	fi
	user_post_start
	touch ${SERVICE_STARTED}
	log_std "done"
	return $RETVAL
}

stop() {
	log "Stopping service ${BINARY_FILE_NAME}."
	if [ -f "${PID_FILE}" ]; then
		kill -15 $(cat ${PID_FILE})
		sleep 1
	fi
	killall -9 ${BINARY_FILE_NAME} > /dev/null 2>&1
	rm -f ${PID_FILE} ${SERVICE_STARTED}
	user_post_stop
	log_std "done"
	return 0
}

restart() {
	log "Restarting service ${BINARY_FILE_NAME}."
	if [ -f ${SERVICE_STARTED} ]; then
		stop
		start
		return $?
	else
		log_std "Service ${BINARY_FILE_NAME} not started - restart suppressed."
		return 1
	fi
}

configure_network() {
	tap="tap0"
  if [ -f ${BRIDGED_SERVICE} ]; then
		openvpn --mktun --dev $tap
		brctl addif ${IFACE} $tap
		ifconfig $tap 0.0.0.0 promisc up
  else
		brctl delif ${IFACE} $tap
		openvpn --rmtun --dev $tap
  fi
}
#end configure_network

reload() {
	log "Reloading service ${BINARY_FILE_NAME}."
  configure_network
	if [ -f $PID_FILE ]; then
		kill -HUP $(cat $PID_FILE) || true
		return $?
	fi
	return 1
}

disable() {
	log "Disable and stopping service ${SERVICE_NAME}."
	rm -rf ${SERVICE_ENABLED}
	stop
	user_disable_script
	rm -rf ${BRIDGED_SERVICE}
	configure_network
	log_std "done"
}

enable() {
  if [ "$VPN_BRIDGED" == "BRIDGED" ]; then
    if [ ! -f ${BRIDGED_SERVICE} ]; then
      touch ${BRIDGED_SERVICE}
      sed -i -e "s|dev tun|dev tap|g" /opt/userdata/etc/openvpn/clientprofiles/*.ovpn
      CHECK=$(pidof ${BINARY_FILE_NAME})
      if [ "${CHECK}" != "" ]; then
        restart
      fi
    fi
  else
    if [ -f ${BRIDGED_SERVICE} ]; then
      rm -rf ${BRIDGED_SERVICE}
      sed -i -e "s|dev tap|dev tun|g" /opt/userdata/etc/openvpn/clientprofiles/*.ovpn
      CHECK=$(pidof ${BINARY_FILE_NAME})
      if [ "${CHECK}" != "" ]; then
        restart
      fi
    fi
  fi
	log "Enable service ${SERVICE_NAME}."
	user_enable_script
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		touch ${SERVICE_ENABLED}
		if [ "$?" == "0" ]; then
			log_std "done"
		else
			log_std "failure"
			exit 1
		fi
	else
		log_std "not available"
	fi
}

status() {
	SERVICE_STATUS="stopped"
	SERVICE_MODUS="disabled"
	RETVAL=0
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		if [ -f ${SERVICE_ENABLED} ]; then
			SERVICE_MODUS="enabled"
		fi
	fi
	CHECK=$(pidof ${BINARY_FILE_NAME})
	if [ "${CHECK}" != "" ]; then
		# assume running because we found a pid
		SERVICE_STATUS="running"
	else
		# ok, not running... should it run?
		if [ -f ${SERVICE_STARTED} ]; then
			# ups should run but not running
			SERVICE_STATUS="failure"
			RETVAL=1
		fi
	fi
	# status did not report in /var/log/messages!
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		echo "${SERVICE_MODUS} / ${SERVICE_STATUS}"
	else
		echo "${SERVICE_STATUS}"
	fi
	exit ${RETVAL}
}

restart_on_failure() {
	SERVICE_STATUS="stopped"
	SERVICE_MODUS="disabled"
	RETVAL=0
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		if [ -f ${SERVICE_ENABLED} ]; then
			SERVICE_MODUS="enabled"
		fi
	fi
	CHECK=$(pidof ${BINARY_FILE_NAME})
	if [ "${CHECK}" != "" ]; then
		# assume running because we found a pid
		SERVICE_STATUS="running"
		# save the pid if we have no pid file:
		if [ ! -f ${PID_FILE} ]; then
				pidof ${BINARY_FILE_NAME} > ${PID_FILE}
		fi
	else
		# ok, not running... should it run?
		if [ -f ${SERVICE_STARTED} ]; then
			SERVICE_STATUS="restarted"
			log_std "Restarted due to failure."
			restart
			RETVAL=$?
		fi
	fi
	# restart_on_failure did not report in /var/log/messages!
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		echo "${SERVICE_MODUS} / ${SERVICE_STATUS}"
	else
		echo "${SERVICE_STATUS}"
	fi
	exit 0
}

configure() {
	if [ "$VPN_BRIDGED" == "BRIDGED" ]; then
		if [ ! -f ${BRIDGED_SERVICE} ]; then
			touch ${BRIDGED_SERVICE}
			sed -i -e "s|dev tun|dev tap|g" /opt/userdata/etc/openvpn/clientprofiles/*.ovpn
		fi
	else
		if [ -f ${BRIDGED_SERVICE} ]; then
			rm -rf ${BRIDGED_SERVICE}
			sed -i -e "s|dev tap|dev tun|g" /opt/userdata/etc/openvpn/clientprofiles/*.ovpn
		fi
	fi
	log_std "Configure service ${SERVICE_NAME}"
	generate_server_config
	reload
	exit 0
}

network_refresh_dhcp_renew() {
		if [ ! -f ${SERVICE_ENABLED} ]; then
			exit 0;
		fi
        log_std "Network refresh"
        if [ "$(grep redirect-gateway /etc/openvpn/server.conf)" != "" ]; then
                VPN_REDIRECT=REDIRECT
        fi
        generate_server_config
        user_post_start
        if [ "${IP_CHANGED}" == "1" ]; then
            log "IP changed restarting OpenVPN service."
            restart
        fi
        exit 0
}

network_refresh() {
		if [ ! -f ${SERVICE_ENABLED} ]; then
			exit 0;
		fi
        log_std "Network refresh"
        if [ "$(grep redirect-gateway /etc/openvpn/server.conf)" != "" ]; then
                VPN_REDIRECT=REDIRECT
        fi
        generate_server_config
        user_post_start
        restart
        exit 0
}

show_config() {
  if [ ! -f /etc/openvpn/server.conf ]; then
    echo "Not configured!"
  exit 1
  fi
  found_version="none"
  if [ -f /etc/openvpn/vpnconfig.version ]; then
    found_version=$(cat /etc/openvpn/vpnconfig.version)
  fi

  if [ "${found_version}" == "${VPNVERSION_CONTENT}" ]; then
    config_state="up to date"
  else
    config_state="deprecated"
  fi
  echo "The configuration is ${config_state}."
  echo "Using DNS server $(grep "dhcp-option DNS" /etc/openvpn/server.conf | cut -d" " -f 4 | sed -e 's/\"//')"
  if [ "$(grep 'dev tun' /etc/openvpn/server.conf)" != "" ]; then
                echo "Configured in routing mode."
        else
                echo "Configured in bridged mode."
        fi
  if [ "$(grep redirect-gateway /etc/openvpn/server.conf)" != "" ]; then
                echo "Configured to redirect gateway and bypass DHCP."
        else
                echo "Configured to route only corresponding traffic to VPN subnet."
        fi
        echo "Generated client profiles:"
  ls /etc/openvpn/clientprofiles
}

# get parameter 
# if parameter is REDIRECT, the server script will be configured to redirect all traffic via VPN, default is off.
# if parameter is bridged, the server script will be configured to create a bridged network default is off.

for i in "$@"
do
case $i in
    start|stop|restart|reload|enable|disable|status|restart_on_failure|configure|network_refresh|dhcp_renew|show_config)
    FUNCTION="${i}"
    shift # past argument=value
    ;;
    REDIRECT)
    VPN_REDIRECT="${i}"
    shift # past argument=value
    ;;
    BRIDGED)
    VPN_BRIDGED="${i}"
    shift # past argument=value
    ;;
    *)
          # unknown option
    ;;
esac
done

case "$FUNCTION" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  reload)
        reload
        ;;
  enable)
        enable
        ;;
  disable)
        disable
        ;;
  status)
        status
        ;;
  restart_on_failure)
        restart_on_failure
        ;;
  configure)
        configure
        ;;
  show_config)
        show_config
        ;;
  network_refresh)
        network_refresh
        ;;
  dhcp_renew)
        network_refresh_dhcp_renew
        ;;
  *)
        log_std "Usage: $0 {${USAGE_STRING}}"
        exit 1
        ;;
esac

exit $?
