# TODO: some kind of automatic (without confirmation) rollback setup?

.PHONY: default
default: copy-configuration-files restart-services

.PHONY: setup
setup: system-dependencies /root/router.wg-pub enable-and-start-services mkinitcpio

.PHONY: firewall-edit
firewall-edit:
	./firewall-edit.bash

.PHONY: mkinitcpio
mkinitcpio:
	mkinitcpio -p linux
	
.PHONY: system-dependencies
system-dependencies:
	echo "Updating system..."
	pacman -Sy --needed archlinux-keyring # get latest keys
	pacman -Syu # update everything
	pacman -S --needed dnsmasq nftables fail2ban radvd git dhcpcd wireguard-tools tailscale # install anything needed
	echo "Done updating system!"
	echo "The system has updated. This usually means the kernel updated, so tailscale needs you to reboot."

.PHONY: restart-services
restart-services:
	echo "Restarting services..."
	systemctl restart nftables
	systemctl restart systemd-sysctl
	systemctl restart systemd-networkd
	systemctl restart dnsmasq
	# systemctl restart systemd-resolved # this seems to conflict with dnsmasq - not sure we need it?
	systemctl restart dhcpcd@lan0
	systemctl restart dhcpcd@wan0
	systemctl restart radvd
	# ksystemctl restart tailscaled # is this necessary since no config lies in this repo?
	echo "Services restarted!"

.PHONY: enable-and-start-services
enable-and-start-services:
	echo "Enabling and starting services..."
	systemctl enable --now nftables
	systemctl enable --now systemd-sysctl
	systemctl enable --now systemd-networkd
	systemctl enable --now dnsmasq
	# systemctl enable --now systemd-resolved # this seems to conflict with dnsmasq - not sure we need it?
	systemctl enable --now dhcpcd@lan0
	systemctl enable --now dhcpcd@wan0
	systemctl enable --now radvd
	# systemctl enable --now tailscaled # is this necessary since no config lies in this repo?
	echo "Services enabled and restarted!"

.PHONY: copy-configuration-files
copy-configuration-files: /etc/dnsmasq.conf /etc/systemd/resolved.conf /etc/sysctl.d/10-router-configs.conf /etc/systemd/network/10-lan0.link /etc/systemd/network/10-wan0.link /etc/dhcpcd.conf /etc/hosts

/root/router.wg-key:
	umask 0077 && wg genkey > $@

/root/router.wg-pub: /root/router.wg-key
	umask 0077 && cat $^ wg genkey > $@
	
/etc/dnsmasq.conf: dnsmasq.conf
	rm -f $@
	cp $^ $@
	
/etc/systemd/resolved.conf: resolved.conf 
	rm -f $@
	cp $^ $@

/etc/sysctl.d/10-router-configs.conf: sysctl-configs
	rm -f $@
	cp $^ $@

/etc/systemd/network/10-lan0.link: lan0.link
	rm -f $@
	cp $^ $@

/etc/systemd/network/10-wan0.link: wan0.link 
	rm -f $@
	cp $^ $@

/etc/dhcpcd.conf: dhcpcd.conf 
	rm -f $@
	cp $^ $@

/etc/hosts: ./etc-hosts 
	rm -f $@ /tmp/etc-hosts
	printf "%s\n" "# DO NOT EDIT DIRECTLY - See router config for details" >> /tmp/etc-hosts
	cat $^ >> /tmp/etc-hosts
	printf "\n\n%s\n" "# DO NOT EDIT DIRECTLY - See router config for details" >> /tmp/etc-hosts
	cp /tmp/etc-hosts $@

/etc/nftables.conf: nftables.conf
	rm -f $@
	cp $^ $@