export KM=CvFpgaKiTi

.SHELL := /bin/bash

# === Hilfsfunktionen =======================================================

OINCDIR:=O
AWK:=awk
DIFF:=diff
CP:=cp
ifndef SVN
SVN:=svn
endif

GEN_SVN_VERSION = @type $(SVN) > /dev/null; \
    if [ $$? -eq 0 ]; then \
        $(SVN) status 2>/dev/null | $(AWK) '/^M/{exit 1}'; \
        if [ $$? -eq 1 ]; then \
            $(SVN) info | $(AWK) '/Last Changed Rev:/||/Letzte ge.nderte Rev:/{sub("\r","",$$4);printf("\#define SVN_REV \"%s*\"\n", $$4);}' > $(OINCDIR)/svn.temp; \
        else \
            $(SVN) info | $(AWK) '/Last Changed Rev:/||/Letzte ge.nderte Rev:/{sub("\r","",$$4);printf("\#define SVN_REV \"%s\"\n", $$4);}' > $(OINCDIR)/svn.temp; \
        fi; \
    else \
        echo > $(OINCDIR)/svn.temp; \
    fi; \
    $(DIFF) $(OINCDIR)/svn.temp $(OINCDIR)/svn.h >/dev/null 2>&1; \
    if [ $$? -ne 0 ]; then \
        $(CP) -f $(OINCDIR)/svn.temp $(OINCDIR)/svn.h; \
    fi; \
    rm $(OINCDIR)/svn.temp

# === Local =================================================================
ifdef LOCAL

-include myconfig

BOARDIP ?= 10.102.12.33

#USER=debian
#PASSWD=temppwd

USER ?= root
PASSWD ?= root

export ARCH:=arm
export CROSS_COMPILE:=/opt/buildroot_tc/arm-buildroot-linux-gnueabihf_sdk-buildroot/bin/arm-buildroot-linux-gnueabihf-
# export CROSS_COMPILE:=arm-linux-gnueabihf-

# KDIR ?= /lib/modules/$(shell uname -r)/build
KDIR ?= /home/user/wsCppSys/vcoctavobr_outDevl/build/linux-4.19.36
# KDIR ?= /opt/bbb_debian10_lx4_19rt_sysroot/lib/modules/4.19.94-ti-rt-r73/build
# KDIR ?= /home/user/opt/linux-headers-4.19.94-ti-rt-r73
# KDIR ?= /home/user/wsCppSys/bbkernel/linux
# KDIR ?= /home/user/wsSbcBox/bbbrout_cvoctavo/build/linux-custom
BUILD_DIR ?= $(PWD)/O
BUILD_DIR_MAKEFILE ?= $(PWD)/O/Makefile

# --- Targets ---------------------------------------------------------------

obj-m += $(KM).o

all: $(BUILD_DIR_MAKEFILE)
	$(GEN_SVN_VERSION)
	$(MAKE) -C $(KDIR) M=$(BUILD_DIR) src=$(PWD) modules

$(BUILD_DIR):
	mkdir -p "$@"

$(BUILD_DIR_MAKEFILE): $(BUILD_DIR)
	touch "$@"

clean:
	$(MAKE) -C $(KDIR) M=$(BUILD_DIR) src=$(PWD) clean
	
upload: all
	sshpass -p $(PASSWD) scp O/$(KM).ko $(USER)@$(BOARDIP):~

run: all upload
	sshpass -p $(PASSWD) ssh $(USER)@$(BOARDIP) "rmmod $(KM); insmod $(KM).ko"
	
stop:
	sshpass -p $(PASSWD) ssh $(USER)@$(BOARDIP) "rmmod $(KM)"

# === Buidlroot =============================================================	
else

obj-m += $(KM).o

prebuild:
	mkdir -p $(OINCDIR)
	echo "#define SVN_REV \"head\"" > O/svn.h

endif