#!/bin/bash
# THIS FILE IS MANAGED BY ANSIBLE, YOUR CHANGES WILL BE LOST!
# This script will maintain your ip rules, routing table and squid config when using wireguard

IFACE=$1
STATE=$2

if [[ "$IFACE" == 'wg0' && "$STATE" == "down" ]]; then
    # When wg0 goes down, remove the wireguard rules to allow traffic again
    ip rule del not from all fwmark 0xca6c lookup 51820 priority 1001
    ip -6 rule del not from all fwmark 0xca6c lookup 51820 priority 1001
fi

if [[ "$STATE" == "up" ]]; then
    # Fix ip rules
    ip rule flush

    ip rule add from all lookup main suppress_prefixlength 0 priority 999
    ip -6 rule add from all lookup main suppress_prefixlength 0 priority 999

    ip rule add fwmark 1 table clearnet priority 1000
    ip -6 rule add fwmark 1 table clearnet priority 1000

    if [[ "$IFACE" == 'wg0' ]]; then
      ip rule add not from all fwmark 0xca6c lookup 51820 priority 1001
      ip -6 rule add not from all fwmark 0xca6c lookup 51820 priority 1001
    fi

    ip rule add from all lookup main priority 32766
    ip -6 rule add from all lookup main priority 32766

    ip rule add from all lookup default priority 32767
    ip -6 rule add from all lookup default priority 32767

    # Flush clearnet table to avoid duplicates
    ip route flush table clearnet
    ip -6 route flush table clearnet

    # Copy all default routes from main table to clearnet table
    ip route show table main | grep '^default' | while read -r route; do
        ip route add table clearnet $route || true
    done

    ip -6 route show table main | grep '^default' | while read -r route; do
        ip -6 route add table clearnet $route || true
    done

    # Get default IPv4 route interface from table 200 (clearnet)
    DEF_IF=$(ip route show table 200 | awk '$1 == "default" {for(i=1;i<=NF;i++) if ($i=="dev") print $(i+1); exit}')

    # Get source IP on that interface
    SRC_IP=$(ip -4 addr show dev "$DEF_IF" | awk '/inet / {print $2}' | cut -d/ -f1 | head -n1)

    # Get IPv4 DNS servers from active connections (not table-bound)
    DNS=$(nmcli dev show "$DEF_IF" | awk '/IP4.DNS/ {print $2}' | paste -sd ' ')

    # Update squid.conf
    sed -i \
      -e "/^dns_nameservers/s|^.*|dns_nameservers $DNS|" \
      -e "/^tcp_outgoing_address/s|^.*|tcp_outgoing_address $SRC_IP|" \
      /etc/squid/squid.conf

    # Reload Squid
    systemctl reload squid
fi
