# check some environment variables first
ifndef ESP8266_RTOS_SDK_DIR
  $(info ESP8266_RTOS_SDK_DIR should be defined as /path/to/sdk directory)
  $(info ESP8266_RTOS_SDK_DIR is set by default to /opt/esp/ESP8266-RTOS-SDK)
  export ESP8266_RTOS_SDK_DIR=/opt/esp/ESP8266-RTOS-SDK
endif

ESP_SDK_DIR = $(ESP8266_RTOS_SDK_DIR)

# With the '-Os' option, char arrays have not to be 32-bit word aligned. This
# leads to an alignment exception when the address of a char array is assigned
# to an 'uint32_t' pointer and the pointer is used for the access.
CFLAGS_OPT ?= -O2

# ESP8266 specific flashing options
FLASH_CHIP  = esp8266
FLASH_OPTS  = --version 3
FLASH_MODE  = dout  # DO NOT CHANGE, ESP8266/ESP8285 modules only work with dout
FLASH_FREQ  = 26m   # DO NOT CHANGE
FLASH_SIZE ?= 1
BOOTLOADER_POS = 0x0000

include $(RIOTCPU)/esp_common/Makefile.include

# regular Makefile

TARGET_ARCH ?= xtensa-esp8266-elf

PSEUDOMODULES += esp_sw_timer

INCLUDES += -I$(RIOTCPU)/$(CPU)
INCLUDES += -I$(RIOTCPU)/$(CPU)/include
INCLUDES += -I$(RIOTCPU)/$(CPU)/vendor
INCLUDES += -I$(RIOTCPU)/$(CPU)/vendor/esp-idf/
INCLUDES += -I$(RIOTCPU)/$(CPU)/vendor/esp-idf/bootloader_support/include
INCLUDES += -I$(RIOTCPU)/$(CPU)/vendor/esp-idf/esp8266/include
INCLUDES += -I$(RIOTCPU)/$(CPU)/vendor/esp-idf/esp8266/include/esp8266
INCLUDES += -I$(RIOTCPU)/$(CPU)/vendor/esp-idf/heap/include
INCLUDES += -I$(RIOTCPU)/$(CPU)/vendor/esp-idf/log/include
INCLUDES += -I$(ESP8266_RTOS_SDK_DIR)/components/
INCLUDES += -I$(ESP8266_RTOS_SDK_DIR)/components/bootloader_support/include/
INCLUDES += -I$(ESP8266_RTOS_SDK_DIR)/components/esp8266/include
INCLUDES += -I$(ESP8266_RTOS_SDK_DIR)/components/esp8266/include/esp8266
INCLUDES += -I$(ESP8266_RTOS_SDK_DIR)/components/heap/include
INCLUDES += -I$(ESP8266_RTOS_SDK_DIR)/components/heap/port/esp8266/include
INCLUDES += -I$(ESP8266_RTOS_SDK_DIR)/components/nvs_flash/include
INCLUDES += -I$(ESP8266_RTOS_SDK_DIR)/components/spi_flash/include

CFLAGS += -D__ESP_FILE__=__FILE__

# NOTE: These can be turned into normal conditionals after #9913 is fixed
GDBSTUB_DIR ?= $(if $(filter esp_gdbstub,$(USEMODULE)),$(RIOTCPU)/$(CPU)/vendor/esp-gdbstub)
CFLAGS     += $(if $(filter esp_gdbstub,$(USEMODULE)),-DGDBSTUB_BREAK_ON_INIT=1)
INCLUDES   += $(if $(filter esp_gdbstub,$(USEMODULE)),-I$(GDBSTUB_DIR))
BASELIBS   += $(if $(filter esp_now, $(USEMODULE)), -lespnow)

BASELIBS += -lgcc -lwpa -lcore -lnet80211 -lphy -lpp -lstdc++

LINKFLAGS += -T$(RIOTCPU)/$(CPU)/ld/esp8266.rom.ld
LINKFLAGS += -T$(RIOTCPU)/$(CPU)/ld/esp8266.riot-os.ld
LINKFLAGS += -T$(RIOTCPU)/$(CPU)/ld/esp8266.peripherals.ld

LINKFLAGS += -Wl,-wrap=pp_attach
LINKFLAGS += -Wl,-wrap=pm_attach