#!/bin/sh
# Install ebtables rules

ebt_match_ipv6_dscp() {
    if [ -n "$BR6_RULE" ]; then
        BR6_RULE="$BR6_RULE --ip6-tclass $1"
    else
        BR_RULE="$BR_RULE --ip6-tclass $1"
    fi
}

broute_rule_set_traffic_class() {
    BR_RULE="$BR_RULE -j mark --mark-or 0x${1}0 --mark-target ACCEPT"
    if [ -n "$BR6_RULE" ]; then
        BR6_RULE="$BR6_RULE -j mark --mark-or 0x${1}0 --mark-target ACCEPT"
    fi
}

broute_filter_on_dscp() {
    BR_RULE="$BR_RULE --ip-tos $1"
}

broute_ipv4_rule_options()
{
    local cid="$1"
    config_get protocol "$cid" "proto"
    config_get dscp_filter "$cid" "dscp_filter"
    config_get icmp_type "$cid" "icmp_type"
    config_get traffic_class "$cid" "traffic_class"

    set_ip_addr "$cid" ebt_match_src_ip ebt_match_dst_ip

    if [ -n "$dscp_filter" ]; then
        local tos_val
        local tos_hex

        tos_val=$((dscp_filter<<2))
        tos_hex=$(printf "%x" $tos_val)
        broute_filter_on_dscp "$tos_hex"
        [ -n "$traffic_class" -a "$dscp_filter" != "0" ] && echo "$((dscp_filter))" >> "/tmp/qos/dscp_values_${traffic_class}_4"
    fi

    if [ -n "$protocol" ]; then
        local proto_num="$(protocol_string_to_num "$protocol")"
        ebt_match_ip_protocol "$proto_num"

        if [ "$proto_num" == "6" ] || [ "$proto_num" == "17" ] || [ "$proto_num" = "132" ] ; then
            set_ports "$cid" ebt_match_ip_src_port ebt_match_ip_dst_port
        elif [ "$proto_num" = "1" -a -n "$icmp_type" ]; then
            ebt_match_ip_icmp_type "$icmp_type"
        fi
    fi
}

broute_ipv6_rule_options()
{
    local cid="$1"

    config_get protocol "$cid" "proto"
    config_get dscp_filter "$cid" "dscp_filter"
    config_get icmp_type "$cid" "icmp_type"
    config_get traffic_class "$cid" "traffic_class"

    set_ip_addr "$cid" ebt_match_ipv6_src_ip ebt_match_ipv6_dst_ip

    if [ -n "$dscp_filter" ]; then
        local tos_val
        local tos_hex

        tos_val=$((dscp_filter<<2))
        tos_hex=$(printf "%x" $tos_val)
        ebt_match_ipv6_dscp "$tos_hex"
        [ -n "$traffic_class" -a "$dscp_filter" != "0" ] && echo "$((dscp_filter))" >> "/tmp/qos/dscp_values_${traffic_class}_6"
    fi

    if [ -n "$protocol" ]; then
        local proto_num="$(protocol_string_to_num "$protocol")"
        ebt_match_ipv6_protocol "$proto_num"

        if [ "$proto_num" = "6" ] || [ "$proto_num" = "17" ] || [ "$proto_num" = "132" ] ; then
            set_ports "$cid" ebt_match_ipv6_src_port ebt_match_ipv6_dst_port
        elif [ "$proto_num" = "58" -a -n "$icmp_type" ]; then
            ebt_match_ipv6_icmp_type "$icmp_type"
        fi
    fi
}

