#!/bin/bash

. /usr/share/groovix/global.conf


#not necessary, seems OK without it, leave it the old way for now in case we manage eth0 with /etc/network/interfaces
#rm /etc/resolv.conf
#ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf

#gncget --mod=644 /etc/network/interfaces.wifi-roam
#mv /etc/network/interfaces /etc/network/interfaces.pre-wpa-supplicant
cp --no-clobber /etc/network/interfaces /etc/network/interfaces.pre-wpa-supplicant
cp /etc/network/interfaces.gx-wifi /etc/network/interfaces

###################################################################
#configure wpa_supplicant-wlan0.conf
if [[ -n "$GX_WIFI_PSK"  ]] ; then
        sed -i "s/GX_WIFI_WPA2_PLACEHOLDER/$GX_WIFI_PSK/" /etc/wpa_supplicant/wpa_supplicant-wlan0.conf
        KEY_TYPE=WPA-PSK
else
        KEY_TYPE=NONE
fi

sed -i "s/GX_WIFI_SSID_PLACEHOLDER/$GX_WIFI_SSID/" /etc/wpa_supplicant/wpa_supplicant-wlan0.conf
sed -i "s/GX_WIFI_KEY_TYPE_PLACEHOLDER/$KEY_TYPE/" /etc/wpa_supplicant/wpa_supplicant-wlan0.conf
###################################################################

###################################################################
# if static address
if [[ -n "$GX_WIFI_STATIC_ADDRESS"  ]] ; then
	cp /var/lib/groovix/gxwifi/10-wlan0-static-ip.network.template /etc/systemd/network/10-wlan0-static-ip.network
	sed -i "s/GX_WIFI_STATIC_ADDRESS_PLACEHOLDER/$GX_WIFI_STATIC_ADDRESS/" /etc/systemd/network/10-wlan0-static-ip.network
	sed -i "s/GX_WIFI_GATEWAY_PLACEHOLDER/$GX_WIFI_GATEWAY/" /etc/systemd/network/10-wlan0-static-ip.network
fi

###################################################################


systemctl enable systemd-resolved.service
systemctl enable systemd-networkd.service
systemctl start systemd-resolved.service
systemctl start systemd-networkd.service

systemctl stop wpa_supplicant
systemctl disable wpa_supplicant
systemctl enable wpa_supplicant@wlan0
systemctl start wpa_supplicant@wlan0

# this is not strictly necessary - the groovix-test-network step would suffice
#make it wait until wlan0 is up:
systemctl enable systemd-networkd-wait-online.service
#/etc/systemd/system/network-online.target.wants/systemd-networkd-wait-online.service to /lib/systemd/system/systemd-networkd-wait-online.service
#get version with --ignore=eth0

#tried it without the enable line that does the link and just creating file, but times out at 2 minutes, get duplicate started update resolvconf for networkd dns messages 
# same thing happens if link is removed and replaced with regular file
# seems we need it to be a link?!?
#rm /etc/systemd/system/network-online.target.wants/systemd-networkd-wait-online.service
#gncget --mod=644 /etc/systemd/system/network-online.target.wants/systemd-networkd-wait-online.service
cp -n /lib/systemd/system/systemd-networkd-wait-online.service /lib/systemd/system/systemd-networkd-wait-online.service.orig
cp /lib/systemd/system/systemd-networkd-wait-online.service.gx-wifi /lib/systemd/system/systemd-networkd-wait-online.service



