# pam/ is at bpftests/pam/, vm-credentials is written to bpftests/controller/
CREDENTIALS_FILE := ../controller/vm-credentials
VM_USER := $(shell sed -n 's/^VM_USER="\(.*\)"/\1/p' $(CREDENTIALS_FILE) 2>/dev/null)

ifeq ($(VM_USER),)
$(error VM_USER is not set. Run build.sh first to generate $(CREDENTIALS_FILE))
endif

VM_IP  := 192.168.100.10
VM_SSH := $(VM_USER)@$(VM_IP)
SSH_OPTS := -o StrictHostKeyChecking=no -o ConnectTimeout=10 -o ServerAliveInterval=5 -o ServerAliveCountMax=3
DECOY_USERS_FILE := ../controller/decoy-users.txt

compile:
	gcc -fPIC -fno-stack-protector -c pam_extension.c -o pam_extension.o
	gcc -shared -o pam_extension.so pam_extension.o -lpam

prepare:
	sudo apt install libpam0g-dev

deploy: pam_extension.c install-remote.sh deploy-remote.sh $(DECOY_USERS_FILE)
	@echo "Building and installing PAM module on $(VM_SSH)..."
	@tar czf - pam_extension.c install-remote.sh deploy-remote.sh | \
	 ssh $(SSH_OPTS) $(VM_SSH) 'sudo -n sh -c '\''set -eu; build_dir=$$(mktemp -d /tmp/.bpfpot-pam.XXXXXX); trap "rm -rf -- $$build_dir" EXIT HUP INT TERM; tar xzf - -C "$$build_dir"; sh "$$build_dir/deploy-remote.sh" "$$build_dir"'\'''
	@set -e; \
	 allowlist="$$(mktemp)"; \
	 trap 'rm -f "$$allowlist"' EXIT HUP INT TERM; \
	 awk -F: -v admin='$(VM_USER)' '\
	   /^[[:space:]]*($$|#)/ { next } \
	   { \
	     user=$$1; pass=$$2; \
	     if (user !~ /^[a-z_][a-z0-9_-]*$$/ || length(user) > 32 || pass == "") { \
	       print "Invalid decoy entry for " user > "/dev/stderr"; bad=1; next; \
	     } \
	     if (user == "root" || user == admin) { \
	       print "Reserved decoy username: " user > "/dev/stderr"; bad=1; next; \
	     } \
	     if (seen[user]++) { \
	       print "Duplicate decoy username: " user > "/dev/stderr"; bad=1; next; \
	     } \
	     users[++count]=user \
	   } \
	   END { if (bad) exit 1; for (i=1; i<=count; i++) print users[i] }' \
	   $(DECOY_USERS_FILE) > "$$allowlist"; \
	 count="$$(wc -l < "$$allowlist")"; \
	 echo "Installing PAM decoy allowlist ($$count users)..."; \
	 ssh $(SSH_OPTS) $(VM_SSH) 'sudo -n install -d -o root -g root -m 0755 /etc/security && sudo -n install -o root -g root -m 0600 /dev/stdin /etc/security/bpfpot-decoy-users' < "$$allowlist"

clean:
	rm -f pam_extension.o pam_extension.so

.PHONY: compile prepare deploy clean
