.PHONY: lint vis clean common client server passwd subpkgs install uninstall reinstall

SUBPKGS = logger spinsult hkexnet
TOOLS = hkexpasswd hkexsh hkexshd
SUBDIRS = $(LIBS) $(TOOLS)

ifeq $(MSYSTEM),MSYS)
	GOOS=windows
endif

ifeq ($(GOOS),windows)
ifeq ($(MSYSTEM),MSYS)
	SBIN=bin
endif
else
	SBIN=sbin
endif

INSTPREFIX = /usr/local

all: common client server passwd

clean:
	go clean .
	for d in $(SUBDIRS); do\
	  $(MAKE) -C $$d clean;\
	done

subpkgs:
	for d in $(SUBPKGS); do\
	  $(MAKE) -C $$d all;\
	done

tools:
	for d in $(TOOLS); do\
	  $(MAKE) -C $$d all;\
	done


common:
	go install .


client: common
	$(MAKE) -C hkexsh


server: common
ifeq ($(GOOS),windows)
ifeq ($(MSYSTEM),MSYS)
	@echo "(GOOS=windows, MSYSTEM=MSYS):hkexshd server not (yet) supported on Windows"
else
	@echo "(GOOS=windows, MSYSTEM=?):Cross-build of hkexshd server not (yet) supported"
endif
else
	$(MAKE) -C hkexshd
endif


passwd: common
ifneq ($(GOOS),windows)
ifeq ($(MSYSTEM),MSYS)
	@echo "(GOOS=windows, MSYSTEM=MSYS): Building hkexpasswd, but won't install until hkexshd works on (windows,MSYS)."
	$(MAKE) -C hkexpasswd
else
	@echo "(GOOS=windows, MSYSTEM=?): unsupported uninstall config."
endif
else
	$(MAKE) -C hkexpasswd
endif

vis:
	@which go-callvis >/dev/null 2>&1; \
	stat=$$?; if [ $$stat -ne "0" ]; then \
	  /bin/echo "go-callvis not found. Run go get github.com/Russtopia/go-callvis to install."; \
	else \
	  make -C hkexsh vis;\
	  make -C hkexshd vis;\
	  make -C hkexpasswd vis; \
	fi

lint:
	make -C hkexpasswd lint
	make -C hkexshd lint
	make -C hkexsh lint

reinstall: uninstall install

install: client server passwd
ifeq ($(GOOS),windows)
ifeq ($(MSYSTEM),MSYS)
	cp hkexsh/hkexsh.exe $(INSTPREFIX)/bin/.hkexsh.exe
	cp hkexsh/hkexsh.exe $(INSTPREFIX)/bin/.hkexcp.exe
	cp hkexsh/mintty_wrapper.sh $(INSTPREFIX)/bin/hkexsh.exe
	cp hkexsh/mintty_wrapper.sh $(INSTPREFIX)/bin/hkexcp.exe
else
	@echo "(GOOS=windows, MSYSTEM=?):unsupported install config."
endif
else
	cp hkexsh/hkexsh $(INSTPREFIX)/bin/hkexsh
	cp hkexshd/hkexshd hkexpasswd/hkexpasswd $(INSTPREFIX)/$(SBIN)
	cd $(INSTPREFIX)/bin && ln -s hkexsh hkexcp && cd -
endif


uninstall:
	rm -f $(INSTPREFIX)/bin/hkexsh* $(INSTPREFIX)/bin/hkexcp* $(INSTPREFIX)/bin/.hkexsh*
	rm -f $(INSTPREFIX)/$(SBIN)/hkexshd* $(INSTPREFIX)/$(SBIN)/hkexpasswd*