# detect OS
ifeq ($(OS),Windows_NT)
    RM  := del /q
    CC  := sdcc
    COM := COM3
else
    RM   := rm -rf

    UNAME_S := $(shell cat /etc/*-release | grep 'DISTRIB_ID' | sed 's/DISTRIB_ID=\(\w*\)/\1/g')
    ifeq ($(UNAME_S),Ubuntu)
    CC  := sdcc
    COM := /dev/ttyUSB0
    endif
    ifeq ($(UNAME_S),Deepin)
    CC  := ablrun sdcc
    COM := /dev/ttyUSB0
    endif
endif

# set uart baudrate
BAUD := 9600

# set CC TOOL
PACKIHX := packihx
CFLAGS := -DUSE_FLOATS=1
LDFLAGS := --iram-size 0x100 --xram-size 0x400 --code-size 0xffff 

# set DIR
INCDIR = include
SRCDIR = src
OBJDIR = obj
TARGET = obj/main.ihx

INC := ./include
SRC := $(wildcard $(SRCDIR)/*.c)
# OBJ := $(SRC:%.c=%.rel)
OBJ := $(patsubst src/%.c, obj/%.rel, $(SRC))  

.PHONY: all clean

all: main.hex

clean:
	-$(RM) obj/*

$(OBJ):obj/%.rel:src/%.c
	-$(CC) $(CFLAGS) -I $(INC) -c $^ -o $@

$(TARGET): $(OBJ)
	-$(CC) $(LDFLAGS) $^ -o $@
	
main.hex: $(TARGET)
	-$(PACKIHX) $(TARGET) > main.hex

flash:
	-sudo chmod 777 $(COM)
	-./reset_mcu.sh $(COM) $(BAUD)
	-stcgal -P stc89 -p $(COM) main.hex

com:
	-minicom -D $(COM) -b $(BAUD)
#led.bin:led.hex
#       objcopy -I ihex -O binary led.hex led.bin

#led.hex:main.ihx
#       packihx main.ihx > led.hex

# led.bin:main.ihx
#         makebin main.ihx led.bin