#!/bin/sh
###############################################################################
#                                                                             #
# IPFire.org - A linux based firewall                                         #
# Copyright (C) 2007-2025  IPFire Team  <info@ipfire.org>                     #
#                                                                             #
# This program is free software: you can redistribute it and/or modify        #
# it under the terms of the GNU General Public License as published by        #
# the Free Software Foundation, either version 3 of the License, or           #
# (at your option) any later version.                                         #
#                                                                             #
# This program is distributed in the hope that it will be useful,             #
# but WITHOUT ANY WARRANTY; without even the implied warranty of              #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               #
# GNU General Public License for more details.                                #
#                                                                             #
# You should have received a copy of the GNU General Public License           #
# along with this program.  If not, see <http://www.gnu.org/licenses/>.       #
#                                                                             #
###############################################################################

. /etc/sysconfig/rc
. ${rc_functions}

PIDFILE="/var/run/openvpn-rw.pid"

# Load configuration
eval $(/usr/local/bin/readhash /var/ipfire/ovpn/settings)

case "${1}" in
	start)
		# Exit if OpenVPN is not enabled
		if [ "${ENABLED}" != "on" ]; then
			exit 0
		fi

		# Load the tun module
		modprobe tun &>/dev/null

		# Flush all firewall rules
		iptables --wait -F OVPNINPUTRW

		# Open the port
		iptables --wait -A OVPNINPUTRW \
			-p "${DPROTOCOL}" --dport "${DDEST_PORT}" -j ACCEPT

		boot_mesg "Starting OpenVPN Roadwarrior Server..."
		loadproc -f /usr/sbin/openvpn \
			--config /var/ipfire/ovpn/server.conf

		boot_mesg "Starting OpenVPN Authenticator..."
		PIDFILE= loadproc /usr/sbin/openvpn-authenticator --daemon
		;;

	stop)
		boot_mesg "Stopping OpenVPN Authenticator..."
		PIDFILE= killproc /usr/sbin/openvpn-authenticator

		boot_mesg "Stopping OpenVPN Roadwarrior Server..."
		killproc /usr/sbin/openvpn

		# Flush all firewall rules
		iptables --wait -F OVPNINPUTRW
		;;

	restart)
		${0} stop
		sleep 1
		${0} start
		;;

	status)
		statusproc /usr/sbin/openvpn
		;;

	log)
		if [ -r "/var/run/openvpn-rw.log" ]; then
			cat "/var/run/openvpn-rw.log"
		fi
		;;

	*)
		echo "Usage: ${0} {start|stop|restart|status}"
		exit 1
		;;
esac
