#!/usr/bin/bash
#post-up /root/vlan.sh enp2s0
# systemctl disable --now $( systemctl list-units --type=service | grep arp | awk '{print $1}' |grep arp)

LAN_if=$1
NL=$'\n'
DANTED_line=''
#LAN_if=$(ip addr show | awk -F" |/" '{gsub(/^ +/,"")}/inet /{print $(NF)}' | grep "^e" | head>
source /root/variable.sh

# Функции
############################################
arp_check () {
	systemctl is-enabled --quiet arpwatch@${LAN_if}$1 || systemctl enable --now arpwatch@${LAN_if}$1 &
#	echo "12"
}
danted_add () {
	DANTED_line+="external: "${LAN_if}$1"${NL}"
}
vlan_add () {
	ip link add link $LAN_if name $LAN_if.$1$2 type vlan id $1
	ip link set dev $LAN_if.$1$2 up
	ip addr add "$3" dev $LAN_if.$1$2
}
iface_add () {
	ip addr add "$2" brd + dev ${LAN_if} label ${LAN_if}$1
#	ifconfig ${LAN_if}$1 "$2" up
}



if [[ -n "$LAN_if" ]]; then
	echo "found interface = "$LAN_if | systemd-cat -t vlan.sh -p info
	danted_add
	arp_check

# Обработка массива VLAN
############################################
	for vl_add in ${!array_vl[*]}
	do
		echo "found interface = "${array_vl[$vl_add]}" with IP "${array_vl_ip[$vl_add]} | systemd-cat -t vlan.sh -p info
		danted_add ".${array_vl[$vl_add]}$vl_add"
		vlan_add ${array_vl[$vl_add]} $vl_add "${array_vl_ip[$vl_add]}"
		arp_check ".${array_vl[$vl_add]}$vl_add"
	done

# Обработка массива IP
############################################
	for ip_add in ${!array_ip[*]}
	do
		echo "found IP $ip_add = "${array_ip[$ip_add]} | systemd-cat -t vlan.sh -p info
		danted_add ":$ip_add"
		iface_add ":$ip_add" ${array_ip[$ip_add]}
		arp_check ":$ip_add"
	done
fi


# Обработка danted
############################################
echo "Danted conf${NL}${DANTED_line}" | systemd-cat -t vlan.sh -p info
cat >/etc/danted.conf <<EOF
logoutput: syslog

internal: wg0 port = 8118
${DANTED_line}
external.rotation: route

socksmethod: none
user.privileged: root
user.unprivileged: nobody

client pass {
 from: 0.0.0.0/0 to: 0.0.0.0/0
 log: error connect disconnect
}

client block {
 from: 0.0.0.0/0 to: 0.0.0.0/0
 log: connect error
}

socks pass {
 from: 0.0.0.0/0 to: 0.0.0.0/0
 log: error connect disconnect
}

socks block {
 from: 0.0.0.0/0 to: 0.0.0.0/0
 log: connect error
}

EOF

# В слуае с bridge - перезапуск вешает комп, не поднимая сеть
# systemctl restart danted
