#!/bin/sh
#
# This script is run by pppd _after_ the link is brought down.
# It should be used to delete routes, unset IP addresses, etc.
#
# This script is called with the following arguments:
#    Arg  Name               Example
#    $1   Interface name     ppp0
#    $2   The tty            ttyS1
#    $3   The link speed     38400
#    $4   Local IP number    12.34.56.78
#    $5   Peer  IP number    12.34.56.99
#

# Reset the PATH environment variable
PATH=/usr/sbin:/sbin:/usr/bin:/bin
export PATH

# Get the current date and time
QUIT_TIME="$(date "+%Y-%m-%d_%H:%M:%S")"

# Extract username, interface name, and peer IP address from arguments
USERNAME="${PEERNAME}"
IFACE="${1}"
TTY="${2}"
PEERIP="${5}"

# Paths and Configuration
USER_LOG="/var/pppoe-user/log/userinfo"
USER_LOG_FILE="${USER_LOG}/${USERNAME}.log"
USER_CONFIG="pppoe-user"
USER_CFGID="$(uci show ${USER_CONFIG} | grep "${USERNAME}" | cut -d '.' -sf 2)"
USER_CONNECT="$(uci get ${USER_CONFIG}.${USER_CFGID}.connect)"
SESSION_PATH="/var/etc/pppoe-user/session"

# Remove the session file
rm -f "${SESSION_PATH}/${USERNAME}.${IFACE}"

# Log the disconnection details
echo "${QUIT_TIME} ${USERNAME} Offline Interface: ${IFACE} IP: ${PEERIP}" >> "${USER_LOG_FILE}"
echo "Connect time: ${CONNECT_TIME} minutes" >> "${USER_LOG_FILE}"
echo "Sent: ${BYTES_SENT} bytes" >> "${USER_LOG_FILE}"
echo "Received: ${BYTES_RCVD} bytes" >> "${USER_LOG_FILE}"

# Calculate and log the sum and average speed
sum_bytes=$((${BYTES_SENT} + ${BYTES_RCVD}))
sum=$(echo "scale=2;${sum_bytes}/1024/1024" | bc)
echo "Bytes sum: ${sum} MB" >> "${USER_LOG_FILE}"
ave=$(echo "scale=2;${sum_bytes}/1024/${CONNECT_TIME}" | bc)
echo "Average speed: ${ave} KB/s" >> "${USER_LOG_FILE}"

# Add an empty line for separation in the log file
echo >> "${USER_LOG_FILE}"

# Log the execution
logger "${QUIT_TIME} ${PEERNAME} ${PEERIP} OFFLINE-USERS >>>>>> The script has been executed!"

exit 0
