#!/usr/sbin/make -f

PASSWDFILE:=/etc/passwd
UCAFILE:=
sysconfdir:=/usr/etc
datarootdir:=/usr/share
bindir:=/usr/bin
PACKAGE_NAME:=thunar-custom-actions
perl_bin:=/usr/sbin/perl
echo_bin:=/usr/sbin/echo
su_bin:=/usr/sbin/su

# passwd file
ifeq ($(PASSWDFILE),)
passwdfile:=$(sysconfdir)/passwd
else
passwdfile:=$(PASSWDFILE)
endif
# uca file path
ifeq ($(UCAFILE),)
ucafile:=.config/Thunar/uca.xml
else
ucafile:=$(UCAFILE)
endif

ifeq ($(wildcard $(passwdfile)),)
$(error passwd-file "$(passwdfile)" does not exist)
endif

system_uca_files = $(wildcard $(datarootdir)/$(PACKAGE_NAME)/system-uca/*.xml)

users = $(shell $(perl_bin) -F: -e 'print "$$F[0]\n" if ($$F[2]>=1000 and $$F[2] <= 9999)' < $(passwdfile))
homedirs = $(shell $(perl_bin) -F: -e 'print "$$F[5]\n" if ($$F[2]>=1000 and $$F[2] <= 9999)' < $(passwdfile))


.PHONY: update remove
.PHONY: update-all remove-all

update::
	@$(echo_bin) "# Merging system-wide Thunar custom actions into your configuration"
	$(call manip_cmd,merge)
remove::
	@$(echo_bin) "# Removing system-wide Thunar custom actions from your configuration"
	$(call manip_cmd,remove)

manip_cmd = cd && $(bindir)/uca-manip -a $(1) -f $(ucafile) -o $(ucafile) $(system_uca_files)

# $(call root_manip_cmd,USER)
define root_manip_cmd
update-all::
	@$(echo_bin) "# Merging system-wide Thunar custom actions into user $(1)'s configuration"
	$(su_bin) -c "$(call manip_cmd,merge)" - $(1)
remove-all::
	@$(echo_bin) "# Removing system-wide Thunar custom actions from user $(1)'s configuration"
	$(su_bin) -c "$(call manip_cmd,remove)" - $(1)
endef

$(foreach user,$(users),$(eval $(call root_manip_cmd,$(user))))

