# -*- mode: makefile-gmake; -*-
SRC := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))

include ../lib/shared.mk
TARGET := $(XDG_DIR)/mbsync
RC_TARGET := ~/.mbsyncrc
TRANSIENT_DIR := $(SRC)/transient


install: | init update

init:
	if (( $$+commands[mbsync] )) ; then
		$(report) header "Setting up mbsync"
		$(mk_link) $(SRC) $(TARGET)
		$(mk_link) $(SRC)/mbsyncrc $(RC_TARGET)
		$(MAKE) -C $(SRC) update_cert
		[[ ! -e ~/.authinfo.gpg ]] \
	 		&& $(report) "warn" "You need to setup the authinfo.gpg run \n    > $(SRC)/mk_authinfo" \
			|| $(report) "debug" "authinfo.gpg already installed"
	else
		$(report) debug "mbsync not installed. Skipping."
	fi

update_cert:
	if [[ ! -e $(TRANSIENT_DIR) ]] ; then
		$(report) debug "$(TRANSIENT_DIR) didn't exist. Creating one."
		mkdir $(TRANSIENT_DIR)
	fi
	echo "" \
		| openssl s_client -starttls imap --connect 127.0.0.1:1143 -showcerts  2>/dev/null \
		| sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p' \
		> $(TRANSIENT_DIR)/bridge.crt \
		&& $(report) pass "Cert from proton bridge downloaded." \
		|| $(report) error "Error while fetching cert. Is bridge running?"



update:

remove:
	$(report) header "Removing mbsync"
	$(rm_link) $(TARGET)
	rm -rf $(TRANSIENT_DIR) ; $(report) "Deleting $(TRANSIENT_DIR)"
	$(rm_link) $(RC_TARGET)
	rm ~/.authinfo.gpg ; $(report) "Deleting authinfo"