.PHONY: dev online-energieausweis all prod backup run-database build-database install-dependencies wait-for-database prod database

DB_CONTAINER_NAME := database
DB_NAME := main
DB_USER := main
DB_PASSWORD := hHMP8cd^N3SnzGRR
DB_PORT := 5432
DB_VOLUME := postgres_data
PERSISTENT_DIR := $(HOME)/persistent/$(APP_NAME)
BACKUP_FILENAME := $(HOME)/backups/$(shell date +"%Y-%m-%d_%H-%M-%S").sql.gz

online-energieausweis:
	bun run dev --host

dev: install-dependencies database online-energieausweis

database:
	docker compose up

backup:
	mkdir -p $(PERSISTENT_DIR)
	- docker exec -t $(DB_CONTAINER_NAME) pg_dump --data-only -U $(DB_USER) $(DB_NAME) | gzip > $(BACKUP_FILENAME)

rundatabase: stop_database
	docker volume rm -f $(DB_VOLUME)
	docker volume create $(DB_VOLUME)
	docker build -t $(DB_CONTAINER_NAME) .
	docker run -d --name $(DB_CONTAINER_NAME) \
		-e POSTGRES_USER=$(DB_USER) \
		-e POSTGRES_PASSWORD=$(DB_PASSWORD) \
		-p $(DB_PORT):5432 \
		-v $(DB_VOLUME):/var/lib/postgresql/data \
		-v $(PERSISTENT_DIR):/persistent \
		$(DB_CONTAINER_NAME)

stop-database:
	-docker stop $(DB_CONTAINER_NAME)
	-docker rm $(DB_CONTAINER_NAME)

wait-fordatabase:
	@while ! docker exec $(DB_CONTAINER_NAME) pg_isready -U $(DB_USER) -h localhost -p $(DB_PORT) > /dev/null 2>&1; do \
		sleep 1; \
	done

restore-backup:
	gunzip -c $(BACKUP_FILENAME) | docker exec -i $(DB_CONTAINER_NAME) psql -U $(DB_USER) -d postgres

install-dependencies:
	bun install
	bunx prisma generate

all:
	mkdir -p ~/logs
	bun run dev 2>&1 | tee ~/logs/`date '+%d-%m-%Y_%H:%M:%S'`.log

prod: install-dependencies run-database
	bun run build
	mkdir -p ~/logs
	mkdir -p ~/persistent/online-energieausweis
	
# Wir müssen sichergehen, dass der Database Container läuft, sonst können wir ihn nicht linken.
	@if [ ! $$(docker ps | grep database | wc -l) -gt 0 ]; then \
		cd ../database; \
		$(MAKE) prod; \
		cd ../online-energieausweis; \
	fi

# - echo "PRIVATE_KEY=$(cat /etc/letsencrypt/live/ibcornelsen.de/privkey.pem | base64 | tr -d '\n')" >> ~/online-energieausweis/.env;
# - echo "CERTIFICATE=$(cat /etc/letsencrypt/live/ibcornelsen.de/fullchain.pem | base64 | tr -d '\n')" >> ~/online-energieausweis/.env;

	- pm2 delete online-energieausweis
	pm2 start --name "online-energieausweis" --log ~/logs/`date '+%d-%m-%Y_%H:%M:%S'`.log --time  bun -- run ./server.ts