BR2_EXTERNAL=../br_external

all: sdcard.img

sdcard.img: root_overlay
sdcard.img: buildroot/.config
	make -C buildroot all
	cp buildroot/output/images/sdcard.img sdcard.img

root_overlay: root_overlay/bin/door.py
root_overlay: root_overlay/etc/door_tokens
root_overlay: root_overlay/etc/dropbear/dropbear_ecdsa_host_key
root_overlay: root_overlay/etc/wpa_supplicant/wpa_supplicant.conf
root_overlay: root_overlay/root/.ssh/authorized_keys
root_overlay: root_overlay/root/key

root_overlay/root/.ssh/authorized_keys: ~/.ssh/id_rsa.pub
	mkdir -p `dirname $@`
	cp $< $@

buildroot/.config: config
	ln -sf ../config $@

root_overlay/etc/door_tokens:
	mkdir -p `dirname $@`
	touch $@

root_overlay/root/key:
	mkdir -p `dirname $@`
	dd if=/dev/urandom of=$@ bs=1 count=16

root_overlay/bin/door.py: door_control/door.py
	mkdir -p `dirname $@`
	cp $< $@

root_overlay/etc/dropbear/dropbear_ecdsa_host_key:
	sh -c 'if [[ ! -f $@ && ! -f $@.openssh ]]; then mkdir -p `dirname $@` && ssh-keygen -t ecdsa -f $@.openssh; fi'

root_overlay/etc/wpa_supplicant/wpa_supplicant.conf:
	mkdir -p `dirname $@`
	@echo "Please enter the passphrase for the space wifi:"
	wpa_passphrase Space > $@

clean:
	make -C buildroot clean
	rm -f sdcard.img
	rm -f root_overlay/root/.ssh/authorized_keys
	rm -f root_overlay/bin/door.py

menuconfig: buildroot/.config
	make -C buildroot menuconfig
	if [[ ! -L buildroot/.config ]]; then mv buildroot/.config config && ln -s ../config buildroot/.config; fi

.PHONY: all clean sdcard.img menuconfig root_overlay root_overlay/etc/dropbear/dropbear_ecdsa_host_key