#!/bin/bash
#
#	/etc/ppp/ip-{up,down} dispatcher script
#	Put your scripts into ip-{up,down}.d/* instead
#
#	Copyright (C) 1997-2022 SUSE LLC
#
#	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 2 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/>.
#
#	Authors:
#		Klaus Franken 25.02.1998
#		Remo Behn 18.07.1998
#		Arvin Schnell 28.02.2002
#		Ludwig Nussel 26.02.2004
#		Marius Tomaschewski <mt@suse.de>
#		Pawel Wieczorkiewicz <pwieczorkiewicz@suse.de>
###
unset POSIXLY_CORRECT ; set +o posix # we are using non-posix bash features
shopt -s nullglob

BASENAME=${0##*/}
INTERFACE=$1
DEVICE=$2
SPEED=$3
LOCALIP=$4
REMOTEIP=$5
IPPARAM=$6

###
### send all output to syslog
###
exec > >(logger -p security.notice -t "$BASENAME") 2>&1
###
### or remove comment chars to trace this script:
###
#exec &>/tmp/$BASENAME.$$.trace
#set -x
#echo 1>&2 "$0: $@"
#env  1>&2

if [ "X$REMOTEIP" = X -o "X$LOCALIP" = X -o "X$INTERFACE" = X ] ; then
	echo "Usage: $0 <INTERFACE> <DEVICE> <SPEED> <LOCALIP> <REMOTEIP>"
	exit 1
fi

TERM=raw
export TERM

filter_ext()
{
	case $1 in
	*.rpm*|*.old|*.bak|*.orig|*.rej|*.scpmbackup|*~|"")
		return 1 ;;
	*)	return 0 ;;
	esac
}

run_script()
{
	local S="$1" ; shift

	if   test -x "/etc/ppp/$S" ; then
		"/etc/ppp/$S" "$@" | logger -p security.notice -t "${S}" 2>&1
	elif test -x "/usr/libexec/ppp/$S" ; then
		"/usr/libexec/ppp/$S" "$@" | logger -p security.notice -t "${S}" 2>&1
	fi
}

get_sorted()
{
	local S ACTION="$1"

	for S in "/etc/ppp/$ACTION/"* "/usr/libexec/ppp/$ACTION/"* ; do
		filter_ext "$S" || continue && echo "${S##*/}"
	done | sort -u
}

run_scripts()
{
	local S ACTION="$1" ; shift

	for S in $(get_sorted "$ACTION" 2>/dev/null) ;  do
		run_script "$ACTION/$S" "$@"
	done
	return 0
}

case $BASENAME in
#
# The ip-up/ip-down scripts are called by pppd on connect / disconnect.
# See also "man 8 pppd" for all up/down script names supported by pppd.
#
*-up|*-down)
	run_scripts "${BASENAME}.d" "$@"
	run_script  "${BASENAME}.local" "$@"
;;

#
# The pre-start/post-stop scripts can be called by the process before starting
# pppd to initialize demand dialing (e.g. to apply dns servers, so a dns query
# triggers pppd to establish connection) and to perform a cleanup on pppd exit.
#
pre-start|post-stop)
	run_scripts "${BASENAME}.d" "$@"
;;
esac

exit 0

