USE_OPENSSL := no

BUILD := $(shell date -u +%Y%m%d-%H%M%S)
OS := $(shell uname -s)

PREFIX = $(DESTDIR)/opt/CronosAgent

ifeq ($(OS), Linux)
  FLAGS += -rdynamic
ifeq ($(USE_OPENSSL), yes)
  FLAGS += -DUSE_OPENSSL
  DEPENDENCIES += openssl
endif
endif

ifeq ($(OS), Darwin)
  FLAGS += -Wno-deprecated-declarations
ifeq ($(USE_OPENSSL), yes)
  FLAGS += -DUSE_OPENSSL -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-migrator/sdk/MacOSX.sdk/usr/include/
  LIBRARIES += crypto
endif
endif

OBJECTS = \
  RingBuffer.o \
  CronosAgent.o

ifneq ($(USE_OPENSSL), yes)
  OBJECTS += sha256.o
endif

FLAGS += -g -fno-omit-frame-pointer -O3 -MMD $(foreach directory, $(DIRECTORIES), -I$(directory)) -DBUILD=\"$(BUILD)\"
LIBS += $(foreach library, $(LIBRARIES), -l$(library))

CC = gcc
CFLAGS += $(FLAGS) -std=gnu99

ifneq ($(strip $(DEPENDENCIES)),)
  FLAGS += $(shell pkg-config --cflags $(DEPENDENCIES))
  LIBS += $(shell pkg-config --libs $(DEPENDENCIES))
endif

all: build

build: $(PREREQUISITES) $(OBJECTS)
	$(CC) $(OBJECTS) $(FLAGS) $(LIBS) -o cronosagent

install:
	install -D -d $(PREFIX)
	install -o root -g root cronosagent $(PREFIX)
	install -o root -g root cronosagent.sh $(PREFIX)
	install -o root -g root cronosagent.conf $(PREFIX)
ifeq ($(OS), Linux)
	install -o root -g root cronosagent-init $(PREFIX)
	install -m 644 -o root -g root cronosagent-monit $(PREFIX)
	install -m 644 -o root -g root cronosagent.service $(PREFIX)
endif
ifeq ($(OS), Darwin)
	install -m 644 -o root -g root cronosagent.plist $(DESTDIR)/Library/LaunchDaemons
endif

clean:
	rm -f $(PREREQUISITES) $(OBJECTS) cronosagent
	rm -f *.d

version:
	echo "#define VERSION $(shell date -u +%Y%m%d)" > Version.h

debian-package:
	./UpdateLog.sh
ifdef ARCH
	dpkg-buildpackage -b -a$(ARCH) -tc
else
	dpkg-buildpackage -b -tc
endif

.PHONY: all build clean install