#
# Copyright (C) Compex
#
# Usage:
#   1) make
#      - build basic Openwrt firmware for WP546
#

# options
CFG_SUFFIX:=-ath9k

OWRT_DIST_SVN_PATH = svn://svn.openwrt.org/openwrt/tags/backfire_10.03
OWRT_DIST_SVN_REV = 20742
OWRT_DIST_LOCAL_PATH = openwrt
OWRT_DIST_DL_PATH = $(HOME)/dl-openwrt
OWRT_DIST_DL_FILE = $(OWRT_DIST_DL_PATH)/openwrt-backfire_10.03.tar.bz2

PATCHES_PATH = patches
CONFIG_PATH = config

all: owrt_checkout owrt_patches build_fw

owrt_checkout:
	[ -e $(OWRT_DIST_DL_PATH) ] || mkdir -p $(OWRT_DIST_DL_PATH)
	if [ ! -e $(OWRT_DIST_LOCAL_PATH) ]; then \
		if [ -e $(OWRT_DIST_DL_FILE) ]; then \
			tar jxf $(OWRT_DIST_DL_FILE); \
		else \
			svn co -r $(OWRT_DIST_SVN_REV) $(OWRT_DIST_SVN_PATH) $(OWRT_DIST_LOCAL_PATH) && \
			tar jcf $(OWRT_DIST_DL_FILE) $(OWRT_DIST_LOCAL_PATH); \
		fi; \
		ln -s $(OWRT_DIST_DL_PATH) $(OWRT_DIST_LOCAL_PATH)/dl; \
	fi
	touch $@

owrt_patches:
	@for i in $(PATCHES_PATH)/*.patch ; do \
	patch -p1 -d $(OWRT_DIST_LOCAL_PATH) < $$i ; \
	done
	rsync -aC files/ $(OWRT_DIST_LOCAL_PATH)/
	touch $@

standard_config:
	cp $(CONFIG_PATH)/wp546$(CFG_SUFFIX).config $(OWRT_DIST_LOCAL_PATH)/.config

build_fw: standard_config
	cd $(OWRT_DIST_LOCAL_PATH) && make

#
# openwrt build directory clean up
#
owrt_clean:
	@echo Warning: Lots of files in $(OWRT_DIST_LOCAL_PATH) directory will be deleted, continue?; read resp; [ "$$resp" = "y" ]
	cd $(OWRT_DIST_LOCAL_PATH) && make clean && svn revert -R .
	cd $(OWRT_DIST_LOCAL_PATH) && svn st package | grep '^?' | tr -d '?' | xargs rm -rf
	cd $(OWRT_DIST_LOCAL_PATH) && svn st target | grep '^?' | tr -d '?' | xargs rm -rf
	rm -f owrt_patches

