#!/bin/bash

cd "$1" || exit 1
ROOTPWD=$(pwd)

for SITEROOT in "$ROOTPWD"/sites/*; do
	# Skip if not a directory
	[ -d "$SITEROOT" ] || continue

	DOMAIN=$(basename "$SITEROOT")
	echo "Processing domain: $DOMAIN"

	mkdir -p "$SITEROOT/site/.well-known/acme-challenge"

	python3 "$ROOTPWD/acme_tiny.py" \
		--account-key "$ROOTPWD/local/tiny_account.key" \
		--csr "$SITEROOT/$DOMAIN.csr" \
		--acme-dir "$SITEROOT/site/.well-known/acme-challenge" \
		> "/tmp/$DOMAIN.crt"

	# check if exists
	if [ -f "$SITEROOT/fullchain.cer" ]; then
		mv "$SITEROOT/fullchain.cer" "$SITEROOT/fullchain.cer.old"
	fi

	mv "/tmp/$DOMAIN.crt" "$SITEROOT/fullchain.cer"

	echo "Renewed certificate for $DOMAIN"
done

sudo /usr/local/bin/nginx -s reload
echo "Nginx reloaded."
