#!/usr/bin/env bash

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

{% for net in route_lists.mycard %}
ip rule add pref 299 to {{net}} lookup main
{% endfor %}

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

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

{% if gateway.isTun %}
DEV={{gateway.dev_or_via}}
ip route add default dev $DEV table {{gateway.mark}}
iptables -t mangle -A PREROUTING ! -p ospf -i $DEV -m set ! --match-set mycard src -j CONNMARK --set-xmark {{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}')
ip route add default via {{gateway.dev_or_via}} dev $DEV table {{gateway.mark}}
iptables -t mangle -A PREROUTING ! -p ospf -i $DEV -m mac --mac-source $MAC -m set ! --match-set mycard src -j CONNMARK --set-xmark {{gateway.mark}}
{% endif %}

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

echo 1 > /tmp/mycard_global_postup_done

exit 0
