#!/bin/bash
# OnDisconnect

IFUP="EXTERNAL_IFACE"
IFDOWN="INTERNAL_IFACE"
LOGIN=$1
IP=$2
CASH=$3
ID=$4
SPEED=`/etc/stargazer/GetSpeed $LOGIN`
UPSPEED=`/etc/stargazer/GetUpSpeed $LOGIN`
SCOUNT="Kbit"

IPT="/sbin/iptables"
tc="/sbin/tc"


# TIME FORMAT
cur_date=`date \+\%Y.\%m.\%d`
cur_time=`date \+\%H:\%M:\%S`

# DELETE RULEZ  IPT
######################################################################
$IPT -t filter -D INPUT -s $IP -j ACCEPT
while [ $? -eq 0 ]
do
$IPT -t filter -D INPUT -s $IP -j ACCEPT
done

$IPT -t filter -D FORWARD -s $IP -j ACCEPT
while [ $? -eq 0 ]
do
$IPT -t filter -D FORWARD -s $IP -j ACCEPT
done

$IPT -t filter -D FORWARD -d $IP -j ACCEPT
while [ $? -eq 0 ]
do
$IPT -t filter -D FORWARD -d $IP -j ACCEPT
done

$IPT -t filter -D OUTPUT -d $IP -j ACCEPT
while [ $? -eq 0 ]
do
$IPT -t filter -D OUTPUT -d $IP -j ACCEPT
done

#########################

declare -i mark=$ID+101
declare -i mark1=$ID+4101

if [ -n "$mark" ]
then
    $IPT -t mangle -D FORWARD -d $IP -j MARK --set-mark $mark
    while [ $? = 0 ]
    do
            $IPT -t mangle -D FORWARD -d $IP -j MARK --set-mark $mark
    done
fi

if [ -n "$mark1" ]
then
    $IPT -t mangle -D FORWARD -s $IP -j MARK --set-mark $mark1
    while [ $? = 0 ]
    do
            $IPT -t mangle -D FORWARD -s $IP -j MARK --set-mark $mark1
    done
fi


#Download
$tc filter del dev $IFDOWN parent 1: protocol ip prio 3 handle $mark fw classid 1:$mark
$tc class del dev $IFDOWN parent 1:1 classid 1:$mark htb rate $SPEED$SCOUNT

#Upload
$tc filter del dev $IFUP parent 1: protocol ip prio 3 handle $mark1 fw classid 1:$mark1
$tc class del dev $IFUP parent 1:1 classid 1:$mark1 htb rate $UPSPEED$SCOUNT
############################################################################


# DAY/NIGHT switcher
/bin/rm /etc/stargazer/dn/$LOGIN


echo "$cur_date $cur_time DISCONNECT: ID-$ID;LOGIN-$LOGIN;IP-$IP;CASH-$CASH" >> /var/stargazer/allconnect.log
