From 56bb36bb8c29160d098325247da67afb6bc245d2 Mon Sep 17 00:00:00 2001
From: Timm Fitschen <timm.fitschen@ds.mpg.de>
Date: Wed, 19 Dec 2018 20:56:56 +0100
Subject: [PATCH] EHN: target _grant tests if user exists

---
 makefile | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/makefile b/makefile
index 4371608..af9ffab 100644
--- a/makefile
+++ b/makefile
@@ -52,6 +52,9 @@ _install:
 comma:=,
 .PHONY: _grant
 _grant:
+	@for host in $(subst $(comma), ,$(DATABASE_USER_HOST_LIST)); do \
+		( $(MYSQL_CMD) $(MYSQL_CONNECTION) -e "SELECT COUNT(*) FROM mysql.user WHERE user='$(DATABASE_USER)' AND host=\"$$host\";" | grep 0 ) || ( echo "The user '$(DATABASE_USER)@$$host' is already in the database. Please use another user or delete her. E.g. with 'mysql -u $(MYSQL_USER) -p -e \"DROP USER $(DATABASE_USER)@$$host;\"'" ; exit 1 ) ; \
+	done
 	@while true; do \
 		printf "\n Please enter the password for $(DATABASE_USER): "; read -s password; \
 		printf "\nPlease repeat the password for $(DATABASE_USER): "; read -s password2; \
@@ -59,7 +62,7 @@ _grant:
 	done ; \
 	echo "" ; \
 	for host in $(subst $(comma), ,$(DATABASE_USER_HOST_LIST)); do \
-		$(MYSQL_CMD) $(MYSQL_CONNECTION) -e "CREATE USER '$(DATABASE_USER)'@'$$host' identified by '$$password';"; \
+		$(MYSQL_CMD) $(MYSQL_CONNECTION) -e "CREATE USER IF NOT EXISTS '$(DATABASE_USER)'@'$$host' identified by '$$password';" ; \
 		$(MYSQL_CMD) $(MYSQL_CONNECTION) -e "GRANT USAGE ON *.* TO '$(DATABASE_USER)'@'$$host';"; \
 		$(MYSQL_CMD) $(MYSQL_CONNECTION) -e "GRANT ALL PRIVILEGES ON *.* TO '$(DATABASE_USER)'@'$$host' WITH GRANT OPTION;"; \
 		$(MYSQL_CMD) $(MYSQL_CONNECTION) -e "GRANT EXECUTE ON *.* TO '$(DATABASE_USER)'@'$$host';"; \
@@ -67,9 +70,6 @@ _grant:
 
 .PHONY: drop-%
 drop-%:
-	@for host in $(subst $(comma), ,$(DATABASE_USER_HOST_LIST)); do \
-		$(MYSQL_CMD) $(MYSQL_CONNECTION) -e "DROP USER '$(DATABASE_USER)'@'$$host';" || true ; \
-	done
 	@$(MYSQLADMIN_CMD) $(MYSQL_CONNECTION) -f drop $(patsubst drop-%,%,$@)
 
 .PHONY: _exists
-- 
GitLab