preseed:=preseed.cfg
iso_dir:=iso_dir
install_dir:=${iso_dir}/install.amd
initrd:=${install_dir}/initrd
initrd_mod:=${initrd}_mod
boot_dir:=${iso_dir}/isolinux
sum_type:=md5sum
chksum_file:=${iso_dir}/${sum_type}.txt

.PHONY: main
main: build

.PHONY: build
build: modified.iso

modified.iso: orig.iso makefile ${preseed} isolinux ../playbook
	if [ -d "${iso_dir}" ]; then chmod +w -R "${iso_dir}" && rm -rf "${iso_dir}"; fi
	7z x -o"${iso_dir}" "$<"
	chmod +w -R "${install_dir}"
	< "${initrd}.gz" gzip -d > "${initrd_mod}"
	echo "${preseed}" | fakeroot cpio -H newc -o -A -F "${initrd_mod}"
	gzip "${initrd_mod}"
	chmod -w -R "${install_dir}"
	mv "${boot_dir}/menu.cfg" "${boot_dir}/menu_installer.cfg"
	cp -r isolinux/* "${boot_dir}"
	cp -r ../playbook "${iso_dir}/playbook"
	rm -rf "${iso_dir}/playbook/credentials"
	chmod +w "${chksum_file}"
	cd "$(dir ${chksum_file})" && "${sum_type}" `find . -follow -type f \! -name "$(notdir ${chksum_file})"` > "$(notdir ${chksum_file})"
	chmod -w "${chksum_file}"
	genisoimage -r -J -b "isolinux/isolinux.bin" -c "isolinux/boot.cat" -no-emul-boot -boot-load-size 4 -boot-info-table -o "$@" "${iso_dir}"
	chmod +w -R "${iso_dir}" && rm -rf "${iso_dir}"

orig.iso: image_info.txt
	curl --location "$$(cat "$<")" > "$@"

.PHONY: clean
clean:
	rm -rf modified.iso

.PHONY: clean-all
clean-all: clean
	rm -rf orig.iso
