# Copyright (c) 2004-2005 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: /var/cvsroot/gentoo-src/rc-scripts/net-scripts/net.modules.d/ipppd,v 1.7.2.4 2005/01/25 10:42:54 uberlord Exp $

# Contributed by Roy Marples (uberlord@gentoo.org)

# char* ipppd_provides(void)
#
# Returns a string to change module definition for starting up
ipppd_provides() {
	echo "isdn"
}

# void ipppd_depend(void)
#
# Sets up the dependancies for the module
ipppd_depend() {
	after macchanger
	before interface
}

# bool ipppd_check_installed(void)
#
# Returns 1 if isnd4k-utils is installed, otherwise 0
ipppd_check_installed() {
	[[ -x /usr/sbin/ipppd ]] && return 0
	${1:-false} && eerror "For ISDN (ipppd) support, emerge net-dialup/isdn4k-utils"
	return 1
}

# bool ipppd_check_depends(void)
#
# Checks to see if we have the needed functions
ipppd_check_depends() {
	local f

	for f in interface_exists interface_variable interface_type clean_pidfile; do
		[[ $( type -t ${f} ) == function ]] && continue
		eerror "ipppd: missing required function ${f}\n"
		return 1
	done

	return 0
}

# bool ipppd_start(char *iface)
#
# Start isdn on an interface
#
# Returns 0 (true) when successful, non-zero otherwise
ipppd_pre_start() {
	local iface=${1} opts itype=$( interface_type ${1} )
	local ifvar=$( interface_variable ${1} ) pidfile="/var/run/ipppd-${iface}.pid"

	# Check that we are a valid isdn interface
	[[ ${itype} != "ippp" && ${itype} != "isdn" ]] && return 0

	# Check that the interface exists
	interface_exists ${iface} true || return 1

	if ! clean_pidfile ${pidfile} ; then
		ewarn "ipppd is already running on ${iface}"
		eend 0
		return 0
	fi

	# Might or might not be set in conf.d/net
	eval opts=\"\$\{ipppd_${ifvar}\}\"

	einfo "Starting ipppd for ${iface}"
	/usr/sbin/ipppd ${opts} pidfile ${pidfile} file /etc/ppp/options.${iface} >${devnull}
	eend $? || return $?

	return 0
}

# bool ipppd_stop(char *iface)
#
# Stop isdn on an interface
# Returns 0 (true) when successful, non-zero otherwise
ipppd_stop() {
	local iface=${1} pidfile="/var/run/ipppd-${1}.pid"

	ipppd_check_installed || return 0
	[[ ! -f ${pidfile} ]] && return 0

	clean_pidfile ${pidfile} && return 0
	local pid=$( cat ${pidfile} ) r=0

	einfo "Stopping ipppd for ${iface}"
	kill -s TERM ${pid}
	if ! process_finished ${pid} ipppd 10 ; then
		kill -s KILL ${pid}
		process_finished ${pid} ipppd 10 || r=1
	fi

	eend ${r}
	return ${r}
}
