.ONESHELL:
SHELL := /bin/bash
# **************************************
# Could be checked with 
# 	tree /etc/opt/solarity/; tree /opt/solarity/; file /var/log/solarity;ls -l /etc/systemd/system/sit*
#
# **************************************

# CONSTANTS
LN = ln -s
#APP_NAME = sit_ewf_app
#TARGET_NAME = ewf_app_standalone
ETC_SOLARITY_DIR = $(DESTDIR)/etc/opt/solarity/
BACKUPS_SOLARITY_DIR = $(DESTDIR)/var/backups/solarity/
INSTALL_DIR = $(DESTDIR)/opt/solarity/
LOG_DIR = $(DESTDIR)/var/log/solarity
BIN_DIR = $(INSTALL_DIR)bin/
DB_DIR = $(INSTALL_DIR)db/
LIB_DIR = $(INSTALL_DIR)lib/
SYS_ENV_DIR = $(DESTDIR)/etc/profile.d/
SOLARITY_SYSTEM_ENV_FILE_NAME = solarity.sh
#FINAL_EXE_DIR = EIFGENs/$(TARGET_NAME)/F_code
ENV_SRC_FILE = etc/opt/solarity/solarity_environment
ENV_TARGET_FILE = $(ETC_SOLARITY_DIR)solarity_environment
#DAEMON_FILE_DIR = $(INSTALL_DIR)etc/systemd
#DAEMON_FILE_NAME = sit-web-service.service
#DAEMON_TARGET_LOCATION = $(DESTDIR)etc/systemd/system
INSTALLATION_DIRS = $(INSTALL_DIR) $(BIN_DIR) $(DB_DIR) $(LIB_DIR) $(BACKUPS_SOLARITY_DIR)
UNINSTALL_DIRS = $(INSTALL_DIR)

# This target will compile all files
all: build
#	: #do nothing

build:
	$(MAKE) -C eiffel/sit-platform/ build
	
install: installation_directories 
#	If root
	@if ! [ "$(shell id -u)" = 0 ];then
		@echo "WARNING: You are not root, run this target as root please"
	fi
#	sit-platform script
	@if [ ! -f "$(ENV_TARGET_FILE)" ]; then 
		@echo '-------------> Setting up environment ' 
		install -m 544 -D $(ENV_SRC_FILE) $(ETC_SOLARITY_DIR)
	fi
	install -m 555 -D opt/solarity/lib/logger.sh $(LIB_DIR)
	install -m 755 -D opt/solarity/bin/sit-platform $(BIN_DIR)
#	$(LN) $(INSTALL_DIR)/sit-platform $(BIN_DIR)
##	DB scripts called by sit-platform script
	install -m 555 -D db/create_database.sql $(DB_DIR)
	install -m 555 -D db/create_tables.sql $(DB_DIR)
	install -m 555 -D db/grant_privileges.sql $(DB_DIR)
	install -m 644 -D etc/profile.d/$(SOLARITY_SYSTEM_ENV_FILE_NAME) $(SYS_ENV_DIR)

	$(MAKE) -C eiffel install
	$(info '-------> You may want to edit the $(ENV_TARGET_FILE) for environment')

uninstall:
	-rm -rf $(UNINSTALL_DIRS)
	-rm -rf $(SYS_ENV_DIR)/$(SOLARITY_SYSTEM_ENV_FILE_NAME)
	echo "You may want to remove the backup directory, but do it manually rm -r $(BACKUPS_SOLARITY_DIR)"
	$(MAKE) -C eiffel uninstall

clean:
	$(MAKE) -C eiffel clean

purge: uninstall
	-rm -rf $(ETC_SOLARITY_DIR)

distclean: clean

installation_directories: 
	@if ! [ "$(shell id -u)" = 0 ];then
		@echo "WARNING: You are not root, run this target as root please"
	fi
	install -d $(BACKUPS_SOLARITY_DIR)
	install -d $(ETC_SOLARITY_DIR)
	install -d $(INSTALL_DIR)
	install -d $(LOG_DIR)
	install -d $(BIN_DIR)
	install -d $(DB_DIR)
	install -d $(LIB_DIR)


.PHONY: all build install clean distclean uninstall
