#!/bin/sh
#
# Author:	kamikaze
# Contact:	kamikaze@bsdforen.de
#
# If vpnc_conf is defined, it will be treated as a list of configuration files
# in vpnc_conf_dir. This managed mode is useful where where vpnc tunnels have
# to be established through other vpnc tunnels.
# You can pass further command line options to vpnc by specifying
# them in vpnc_flags.
#

# PROVIDE: vpnc
# REQUIRE: LOGIN
# KEYWORD: shutdown

# Default settings - don't change this.
: ${vpnc_enable="NO"}
: ${vpnc_pid_dir="/var/run"}
: ${vpnc_pid_file="vpnc/pid"}
: ${vpnc_conf_dir="%%PREFIX%%/etc"}
: ${vpnc_record="$vpnc_pid_dir/vpnc.record"}

. /etc/rc.subr

name="vpnc"
rcvar=vpnc_enable

command="%%PREFIX%%/sbin/$name"

vpnc_start() {
	if [ -z "$vpnc_conf" ]; then
		#No configuration files given, run unmanaged.
		$command $vpnc_flags
		return $?
	fi

	# A list of configurations is present. Connect managing
	# what is required for a clean shutdown later.

	for config in $vpnc_conf; do

		# The current configuration file.
		current="$vpnc_conf_dir/$config"

		# Start vpnc.
		$command --local-port 0 $current $vpnc_flags
		status=$?
		if [ $status -ne 0 ]; then
			# VPNC does not print a newline after an error.
			echo
			echo "Running 'vpnc $current --local-port 0 $vpnc_flags' failed."
			return $status
		fi

		# Wait for the system to catch up.
		/bin/sleep 1

		# Copy files to allow a clean shutdown
		# of multiple connections.

		/bin/cp "$vpnc_pid_dir/$vpnc_pid_file" "$vpnc_pid_dir/vpnc.$config.pid"
		/bin/cp "$vpnc_pid_dir/vpnc.defaultroute" "$vpnc_pid_dir/vpnc.$config.defaultroute" 2> /dev/null
		/bin/cp "$vpnc_pid_dir/vpnc.resolv.conf-backup" "$vpnc_pid_dir/vpnc.$config.resolv.conf-backup" 2> /dev/null
		echo "$config" >> "$vpnc_record"
	done
}

vpnc_stop() {
	if [ ! -e "$vpnc_record" ]; then
		/bin/sleep 1
		# There's no record of connections, assume unmanaged shutdown.
		$command-disconnect
		return $?
	fi

	# A record of vpnc connections is present. Attempt a
	# managed shutdown.

	for config in `/usr/bin/tail -r "$vpnc_record"`; do

		# Wait to give the system a chance to catch up with
		# recent changes.

		/bin/sleep 1

		# Move the vpnc files back into position.

		/bin/mv "$vpnc_pid_dir/vpnc.$config.pid" "$vpnc_pid_dir/$vpnc_pid_file"
		/bin/mv "$vpnc_pid_dir/vpnc.$config.defaultroute" "$vpnc_pid_dir/vpnc.defaultroute" 2> /dev/null
		/bin/mv "$vpnc_pid_dir/vpnc.$config.resolv.conf-backup" "$vpnc_pid_dir/vpnc.resolv.conf-backup" 2> /dev/null

		# Run the disconnect command.
		$command-disconnect
	done

	# Remove the connection record.

	/bin/rm "$vpnc_record"
}

start_cmd=vpnc_start
stop_cmd=vpnc_stop

load_rc_config $name
run_rc_command "$1"