#!/bin/bash
#OnConnect

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

IPT="/sbin/iptables"
tc="/sbin/tc"
arpcmd="/usr/sbin/arp"
cur_date=`date \+\%Y.\%m.\%d`
cur_time=`date \+\%H:\%M:\%S`

# DELETE RULEZ
######################################################################
$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
#######################################################################

# ADD RULEZ
#######################################################################
$IPT -t filter -A INPUT -s $IP -j ACCEPT
$IPT -t filter -A FORWARD -s $IP -j ACCEPT
$IPT -t filter -A FORWARD -d $IP -j ACCEPT
$IPT -t filter -A OUTPUT -d $IP -j ACCEPT

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

# fix user mac to ip
$arpcmd -d $IP $MAC
while [ $? -eq 0 ]
do
$arpcmd -d $IP $MAC
done
$arpcmd -s $IP $MAC

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

declare -i mark=$ID+101
declare -i mark1=$ID+4101
$IPT -t mangle -A FORWARD -d $IP -j MARK --set-mark $mark
$IPT -t mangle -A FORWARD -s $IP -j MARK --set-mark $mark1

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

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

# DAY/NIGHT switcher
/bin/echo $SPEED:`expr $ID + 4101` > /etc/stargazer/dn/$LOGIN


# ADD TO LOG
echo "$cur_date $cur_time CONNECT: ID-$ID;LOGIN-$LOGIN;IP-$IP;CASH-$CASH;SPEED-$SPEED;UPSPEED-$UPSPEED,MAC-$MAC" >> /var/stargazer/allconnect.log
