#!/bin/sh

busybox killall -9 l2tp_dialer
busybox killall -9 l2tp-ip-up
busybox killall -9 l2tp-ip-down
! rm /etc/l2tp/l2tp-control
    
if [ -f /etc/l2tp/xl2tpd.conf ]; then
    logger "L2TP: needs to be started"
else
    logger "L2TP: no config"
    exit 1
fi

chmod 0600 /etc/ppp/chap-secrets

while true
do

    COUNT_XL2TPD="$(ps aux | grep -c xl2tpd)"
    if [ "$COUNT_XL2TPD" -le "1" ]; then
        logger "L2TP: xl2tpd error, restarting"
        # xl2tpd -D [-c <config file>] [-s <secret file>] [-p <pid file>]  [-C <control file>]
        /usr/sbin/xl2tpd -c /etc/l2tp/xl2tpd.conf -p /tmp/xl2tpd.pid  -C /etc/l2tp/l2tp-control
    fi

    if [ -f /etc/l2tp/dialer.conf ]; then
        COUNT_DIALER="$(ps aux | grep -c l2tp_dialer)"
        if [ "$COUNT_DIALER" -le "1" ]; then
            logger "L2TP: dialer error, restarting"
            /usr/local/bin/l2tp/l2tp_dialer /etc/l2tp/dialer.conf /etc/l2tp/l2tp-control > /dev/null 2>&1 &
        fi
    fi

    sleep 360
done

