CONTAINER := phi_slapd

.PHONY: all
all: build run

.PHONY: build
build: gen-cert
	docker build --no-cache -t unit/slapd .

.PHONY: gen-cert
gen-cert:
	openssl req \
		-x509 -nodes -days 365 -sha256 \
		-subj '/C=IT/ST=Lombardia/L=Milano/CN=localhost' \
		-newkey rsa:2048 -keyout key.pem -out cert.pem

.PHONY: clean
clean:
	rm -f key.pem cert.pem

.PHONY: run
run: prepare
	docker attach phi_slapd

.PHONY: prepare
prepare:
	docker run -p 389:389 -d --name="$(CONTAINER)" --rm unit/slapd
	sleep 2
	LDAPTLS_REQCERT=never \
		ldapmodify -ZZ -H ldap://127.0.0.1:389 \
		-x -D "cn=root,dc=unit,dc=macaomilano,dc=org" -w root \
		-a -f init.ldif

.PHONY: run-bg
run-bg:
	make prepare

.PHONY: stop
stop: is-running
	docker stop $(CONTAINER)

.PHONY: is-running
is-running:
	@[[ $$(docker ps -qf=name=$(CONTAINER)|wc -l) -eq 1 ]]

.PHONY: inspect
inspect: is-running
	LDAPTLS_REQCERT=never \
		ldapsearch -ZZ -H ldap://127.0.0.1 \
		-x -D "cn=root,dc=unit,dc=macaomilano,dc=org" -w root \
		-b "dc=unit,dc=macaomilano,dc=org" \
		'(objectclass=*)'