#The main purpose of this Makefile is to copy the given rule file into the udev rule directory.
#It uses a loop to check if a rule file with the same name already exists. If it exists, it will
#increment the index and update the name of the new rule file to the new index. Once an available 
#name is found, it will move the rule file to the udev directory

# Define variables
INSTALL_DIR=/usr/local/sbin/gwscript
RULES_DIR=/etc/udev/rules.d/
RULES_NAME=50-programmer_usb.rules
SRC_DIR = .


all: copy_udev_rules




copy_udev_rules: check_file
	@cp -p $(SRC_DIR)/$(RULES_NAME) $(RULES_DIR)
	@echo "File $(RULES_NAME) has been copied to $(RULES_DIR)"


#Check if the file exists
check_file: check_system
	@n=50;RULES_AFTER=/etc/udev/rules.d/50-programmer_usb.rules; while [ -f $$RULES_AFTER ] && [ $$n -lt 100 ]; do \
		n=$$((n+1)); \
		RULES_AFTER=/etc/udev/rules.d/$${n}-programmer_usb.rules; \
		sleep 1; \
	done; \
	if [ ! $$n -ge 50 ]; then \
		mv $(RULES_DIR)$(RULES_NAME) $$RULES_AFTER; \
	fi


check_system: 
	@if [ -f "/etc/redhat-release" ]; then \
		length=$$(cat /etc/redhat-release | awk '{print NF}'); \
		length=$$((length - 1)); \
		system=$$(cat /etc/redhat-release | awk '{print $$'"$length"'}'); \
		first_char=$${system:0:1}; \
		if [ $$((first_char)) -eq 6 ]; then \
			echo "Please restart the system later to complete the setup"; \
		fi; \
	fi

