TOPDIR:=.
TGT:=../bin/restproxy

DIR=$(TOPDIR)
SRCS=$(foreach dir, $(DIR), $(wildcard $(dir)/*.c))
OBJS:=$(patsubst %.c,%.o,$(SRCS))

DIR_LIBEVENT = ./third-lib/libevent/include/
DIR_JSON = ./third-lib/libmjson/src/
DIR_CURL = ./third-lib/libcurl/include/curl/

INCDIR = $(foreach dir, $(DIR), -I $(dir)/ )
INCDIR += -I $(DIR_LIBEVENT)
INCDIR += -I $(DIR_JSON)
INCDIR += -I $(DIR_CURL)

LIBS = ./dba/lib/libdba.a ./smcli_client/lib/libclient.a 
LIBS += ./pstn_cli/lib/libpstncli.a ./tcp/lib/libtcp.a 
LIBS += /usr/lib/x86_64-linux-gnu/libidn.a -I/usr/include/mysql -L/usr/lib64/mysql -lmysqlclient 
LIBS += ./third-lib/libcurl/lib/.libs/libcurl.a -lrt -lcrypto -lssl -lpthread 
LIBS += ./third-lib/libevent/.libs/libevent.a ./third-lib/libevent/.libs/libevent_pthreads.a 
LIBS += ./third-lib/libmjson/src/.libs/libmjson.a  -L/usr/local/lib -lglib-2.0 -lz -lidn2

CFLAGS = -Wall -g -DX86_64 -DTEST_RESTPROXY $(LIBS) 

CONFIGURE = ./configure

CC = gcc

$(TGT): lib_all 3rdlib_all $(OBJS) 
	if [ ! -d ../bin ]; then mkdir ../bin; fi
	$(CC) -o $(TGT) $(CFLAGS) $(SRCS) $(INCDIR) $(LIBS)
	chmod a+x $(TGT)

$(OBJS): %.o:%.c
	$(CC) $(CFLAGS) -c -o $@ $< $(INCDIR)

all: $(TGT)

clean_all: clean lib_clean 3rdlib_clean

lib_all:
	$(MAKE) -C ./smcli_client
	$(MAKE) -C ./pstn_cli
	$(MAKE) -C ./tcp
	$(MAKE) -C ./dba

3rdlib_prepare:
	if [ ! -d ./third-lib/libevent ]; then \
		tar -xvf ../backup/libevent-2.1.11-stable.tar.gz -C ./third-lib/; \
		mv ./third-lib/libevent-2.1.11-stable ./third-lib/libevent; \
	fi
	if [ ! -d ./third-lib/libcurl ]; then \
		tar -xvf ../backup/curl-7.52.1.tar.gz -C ./third-lib/; \
		mv ./third-lib/curl-7.52.1 ./third-lib/libcurl; \
	fi
	if [ ! -d ./third-lib/libmjson ]; then \
		tar -xvf ../backup/mjson-1.7.0.tar.gz -C ./third-lib/; \
		mv ./third-lib/json-1.7.0 ./third-lib/libmjson; \
	fi

3rdlib_config: 3rdlib_prepare
	cd ./third-lib/libevent && $(CONFIGURE)
	cd ./third-lib/libcurl && $(CONFIGURE)
	cd ./third-lib/libmjson && $(CONFIGURE)

3rdlib_all:
	$(MAKE) -C ./third-lib/libevent
	$(MAKE) -C ./third-lib/libcurl
	$(MAKE) -C ./third-lib/libmjson

lib_clean:
	$(MAKE) -C ./smcli_client clean
	$(MAKE) -C ./pstn_cli clean
	$(MAKE) -C ./tcp clean	
	$(MAKE) -C ./dba clean

3rdlib_clean:
	$(MAKE) -C ./third-lib/libevent clean
	$(MAKE) -C ./third-lib/libcurl clean
	$(MAKE) -C ./third-lib/libmjson clean	

clean:
	rm -rf $(OBJS) $(TGT)
