#
#   play with firmware
#
#   Copyright (C) 2004 Enrik Berkhan <enrik.berkhan@inka.de>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   what you need:
#   - wget (or get original manually)
#   - busybox tar
#   - sudo or equivalent
#   - squashfs in kernel (have a look at dmesg, re-load module after oopses ;-)
#
#   *** USE AT YOUR OWN RISK ***
#

ORIG_FW := fritz.box_fon.06.01.135.image

Archive/$(ORIG_FW):
	-mkdir Archive
	( cd Archive && \
	  rm -f $(ORIG_FW); \
	  wget --passive-ftp ftp://ftp.avm.de/cardware/fritzbox.fon/firmware/$(ORIG_FW) \
	)

orig-fw: Archive/$(ORIG_FW)
	rm -rf orig-fw
	mkdir orig-fw
	( cd orig-fw && busybox tar xvf ../Archive/$(ORIG_FW) )

root-fs var-fs: orig-fw
	rm -rf root-fs
	rm -rf var-fs
	mkdir root-fs var-fs
	-mkdir image
	sudo mount -o loop orig-fw/var/tmp/filesystem.image ./image
	sudo cp -a ./image/* ./root-fs
	sudo chown -R $$LOGNAME root-fs
	( cd var-fs && busybox tar xvf ../root-fs/var.tar )
	sudo umount ./image
	-rmdir image

root-fs/var.tar: | root-fs var-fs
root-fs/var.tar: $(shell find var-fs -type f 2>/dev/null)
	rm -f root-fs/var.tar
	( cd var-fs && busybox tar cvf ../root-fs/var.tar ./var )

update: | root-fs var-fs
update: $(shell find root-fs -type f 2>/dev/null)
	rm -rf update
	-mkdir update
	cp -a orig-fw/var update
	( cd update/var/tmp; \
	  rm -f filesystem.image; \
	  mksquashfs ../../../root-fs filesystem.image -le; \
	  tichksum filesystem.image; \
	  tichksum urlader.Fritz_Box_FON.image; \
	)
	# TODO: check filesystem.image size < 3MB

fritz.image: update
	rm -f fritz.image
	( cd update && busybox tar cvf ../fritz.image ./var )

extract: root-fs var-fs

clean:
	rm -rf orig-fw root-fs var-fs update

realclean: clean
	rm -rf Archive

patch-telnet: clean
	$(MAKE) root-fs
	patch -p0 < rc.net.telnet.diff
	$(MAKE) fritz.image
	mv fritz.image fritz.telnet.image

.PHONY: extract clean realclean patch-telnet
