#!/bin/sh

ignore_tos=$(grep "^ignore_tos=" /etc/shaper/shaper.0.cfg | grep -E "yes|1" | wc -l)

if [ $ignore_tos -eq 1 ];then
    iptables -N shaign0 2>/dev/null
    iptables -t mangle -N shaign0 2>/dev/null

    if [ $(iptables -vxL FORWARD -n | grep shaign0 | wc -l) -eq 0 ];then
        iptables -I FORWARD -m tos --tos 0x02 -j shaign0
    fi
    if [ $(iptables -t mangle -vxL FORWARD -n | grep shaign0 | wc -l) -eq 0 ];then
        iptables -t mangle -A FORWARD -j shaign0
    fi
    if [ $(iptables -vxL INPUT -n | grep shaign0 | wc -l) -eq 0 ];then
        iptables -I INPUT -m tos --tos 0x02 -j shaign0
    fi
    if [ $(iptables -t mangle -vxL INPUT -n | grep shaign0 | wc -l) -eq 0 ];then
        iptables -t mangle -A INPUT -j shaign0
    fi
    if [ $(iptables -vxL OUTPUT -n | grep shaign0 | wc -l) -eq 0 ];then
        iptables -I OUTPUT -m tos --tos 0x02 -j shaign0
    fi
    if [ $(iptables -t mangle -vxL OUTPUT -n | grep shaign0 | wc -l) -eq 0 ];then
        iptables -t mangle -A OUTPUT -j shaign0
    fi
    if [ $(iptables -t mangle -vxL PREROUTING -n | grep "TOS.*match.*0x02.*TOS.*set.*0x00" | wc -l) -eq 0 ];then
	iptables -t mangle -I PREROUTING -m tos --tos 0x02 -j TOS --set-tos 0x00
    fi

    if [ ! -f /etc/shaper/ignore_tos.0 ];then touch /etc/shaper/ignore_tos.0; fi

    iptables -F shaign0
    iptables -t mangle -F shaign0

    OLDIFS=$IFS
    IFS=';'

    grep -E -v "^#|^$" /etc/shaper/ignore_tos.0 | while read prot src sport dst dport
    do
        if [ "$src" == "*" ];then
            src="0/0"
        fi
        if [ "$dst" == "*" ];then
            dst="0/0"
        fi
        if [ "$sport" == "*" ];then
            sport="0:65535"
        fi
        if [ "$dport" == "*" ];then
            dport="0:65535"
        fi
        if [ "$prot" != "icmp" ];then
            iptables -t mangle -I shaign0 -p $prot -s $src --sport $sport -d $dst --dport $dport -j TOS --set-tos 0x02
            iptables -I shaign0 -p $prot -s $src --sport $sport -d $dst --dport $dport
        else
            iptables -t mangle -I shaign0 -p $prot -s $src -d $dst -j TOS --set-tos 0x02
        fi
    done
else
    echo "Opcja ignore_tos jest wylaczona!"
    exit 1
fi

IFS=$OLDIFS
exit 0
