#!/usr/bin/env bash

# ipset
{% for list in route_list_names %}
ipset restore -f /etc/wireguard/{{list}}.ipset
{% endfor %}

# 针对网关设置mark
{% for gateway in gateways %}

{% if gateway.dev_or_via != "" %}

{% if gateway.isTun %}
DEV={{gateway.dev_or_via}}
IPTABLES_MARK_CONDITION="-i $DEV"
ip route add default dev $DEV table {{gateway.mark}}
{% else %}
ping {{gateway.dev_or_via}} -c 1
NEIGH_LINE=$(ip neigh show {{gateway.dev_or_via}})
DEV=$(echo $NEIGH_LINE | awk '{print $3}')
MAC=$(echo $NEIGH_LINE | awk '{print $5}')
IPTABLES_MARK_CONDITION="-i $DEV -m mac --mac-source $MAC"
ip route add default via {{gateway.dev_or_via}} dev $DEV table {{gateway.mark}}
{% endif %}

bash -c "iptables -t mangle -A PREROUTING $IPTABLES_MARK_CONDITION -m set ! --match-set mycard src -j CONNMARK --set-xmark {{gateway.mark}} ; iptables -t mangle -A PREROUTING -m connmark --mark {{gateway.mark}} -j CONNMARK --restore-mark ; iptables -t mangle -A OUTPUT -m connmark --mark {{gateway.mark}} -j CONNMARK --restore-mark"

{% endif %}

ip rule add pref 301 fwmark {{gateway.mark}} lookup {{gateway.mark}}

{% endfor %}

# 临时梯子
iptables -t mangle -A PREROUTING -m set --match-set ladder_needed src -m set --match-set gfwiplist dst -j MARK --set-xmark 812/0xffffffff

exit 0
