#!/usr/bin/env bash
# ${1} : environment (see README.md)
module_names=''
echo -e "* Auto-create wired profil, autoconnect service for netctl and polybar module..."
for i in `ip -br l | awk '$1 !~ "lo|vir|br|wl" { print $1}'`; do
    echo -e "~ ${i}..."
	module_name="network-${i}"
	module_names+=" ${module_name}" 
    cat <<- EOF | sudo tee /etc/netctl/${i} >/dev/null
		Interface=${i}
		Connection=ethernet
		IP=dhcp
	EOF
	cat <<- EOF | tee ~/.config/polybar/config.d/${i}.${1} >/dev/null
		[module/${module_name}]
		type = internal/network
		interface = ${i}
		ping-interval = 3
		label-connected = \${env:BAR_WIRED_CONNECTED}
		label-disconnected = 
		label-disconnected-foreground = \${colors.text}
		; Consider an 'UNKNOWN' interface state as up.
		; Some devices like USB network adapters have 
		; an unknown state, even when they're running
		; Default: false
		unknown-as-up = true
	EOF
	sudo systemctl enable --now netctl-ifplugd@${i}
	# In case some old config stays....
	sudo systemctl restart netctl-ifplugd@${i}

done
echo -e "* Autoconnect to wireless profiles..."
for i in `ip -br l | awk '$1 ~ "wl" { print $1}'`; do
	module_name="network-${i}"
	module_names+=" ${module_name}" 
	echo -e "~ ${i}..."
	cat <<- EOF | tee ~/.config/polybar/config.d/${i}.${1} >/dev/null
		[module/${module_name}]
		type = internal/network
		interface = ${i}
		ping-interval = 3
		label-connected = \${env:BAR_WIFI_CONNECTED}
		label-disconnected = 
		label-disconnected-foreground = \${colors.text}
	EOF
	sudo systemctl enable --now netctl-auto@${i}
done
echo -e "* Create an override polybar file to add all discovered networks..."
cat << EOF | tee ~/.config/polybar/config.d/bottom_center.${1} >/dev/null
[variables]
bottom_center = updates-arch-combined ${module_names}
EOF
# https://man.archlinux.org/man/netctl.special.7
echo -e "* Ensure connections are back when PC is resumed..."
sudo systemctl enable netctl-sleep