#!/bin/bash

###########################################################################
#
# MODULE:       Scripts
# COPYRIGHT:    (C) 2009-2025 by CacheGuard Technologies Ltd (UK)
# COPYRIGHT:    (C) 2026-2026 by CacheGuard Technologies SAS (FR)
#
# 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/>.
#
###########################################################################

CACHEGUARD_DIR=/etc/sysconfig/cacheguard
source ${CACHEGUARD_DIR}/constant

source /lib/lsb/init-functions

pppoe-up()
{
    test -n "${1}" || return 1
    local dev=${1}

    local timeout=3000000 gap=200000
    local n=$((timeout / gap)) i=0

    pppd nodetach call ${EXTERNAL_PPPOE_PEER_NAME} \
	 ip-up-script ${LOCAL_DIR}/bin/apl_pppoe_up \
	 ip-down-script ${LOCAL_DIR}/bin/apl_pppoe_down > /dev/null 2>&1 &

    local pid=${!}

    echo ${pid} > /var/run/pppoe.pid

    while ! ip -4 address show dev ${EXTERNAL_PPPOE_IF} > /dev/null 2>&1
    do
	test ${i} -lt ${n} || break
	usleep ${gap}
	((i++))

	if ! kill -0 "${pid}" 2> /dev/null ; then
            wait "${pid}"
            local ret=$?
            echo "pppd exited with ${ret}" > /dev/null
            return ${ret}
	fi
    done

    test ${i} -ne ${n}
}

pppoe-down()
{
    test -n "${1}" || return 1
    local dev=${1}

    local prog='pppd'
    local timeout=3000000 gap=200000
    local n=$((timeout / gap)) i=0

    local pid=$(cat /var/run/pppoe.pid 2>/dev/null)
    test -n "${pid}" || pid=$(pidof ${prog} 2> /dev/null)

    rm -f /var/run/pppoe.pid

    if test -n "${pid}" && kill -0 "${pid}" 2>/dev/null ; then
        kill -TERM "${pid}" 2>/dev/null

	while kill -0 "${pid}" 2>/dev/null
	do
	    test ${i} -lt ${n} || break
	    usleep ${gap}
	    ((i++))
	done

	if test ${i} -eq ${n} ; then
	    kill -KILL "${pid}" 2>/dev/null
	    usleep ${timeout}
	fi
    else
	killall --quiet -TERM ${prog}
	usleep ${timeout}
	killall --quiet -KILL ${prog}
	usleep ${timeout}
    fi

    
    return 0
}

case "${2}" in
    up)
	log_info_msg "Bringing up PPPoE for ${1}..."
	pppoe-up ${1}
	evaluate_retval
	;;
    down)
	log_info_msg "Bringing down PPPoE for ${1}..."
	pppoe-down ${1}
	evaluate_retval
	;;
    *)
	echo "Usage: ${0} [interface] {up|down}"
	exit 1
	;;
esac
