#!/bin/bash
set -e

if [ -n "$1" ]; then
	cd "$1" || echo "no first argument passed, staying in cwd"
fi

ROOTPWD=$(pwd)
# this awkward method is used for portability
ROOTPWDOWNER=$(ls -ld $ROOTPWD | awk '{printf "%s", $3}')

# change to owner of host/ if running as root
# prevents nginx being unable to read files owned by root
if [ "$(id -u)" -eq 0 ]; then
	echo "switching to $ROOTPWDOWNER in order to preserve permissions"
	exec sudo -u $ROOTPWDOWNER "$0" "$@"
fi

KEYFILE="$ROOTPWD/local/tiny_account.key"
for SITEROOT in "$ROOTPWD"/sites/*; do
	{
		# Skip if not a directory
		[ -d "$SITEROOT" ] || continue

		DOMAIN=$(basename "$SITEROOT")
		SSLDIR="$SITEROOT/ssl"
		CSRFILE="$SSLDIR/$DOMAIN.csr"
		FULLCHAIN="$SSLDIR/fullchain.cer"
		CHALLENGEDIR="$SSLDIR/.well-known/acme-challenge"
		TMPOUT="$SSLDIR/$DOMAIN.crt.tmp"
		echo "Processing domain: $DOMAIN"

		# local_https.sh does not create a csr file, assume
		# it is a self-signed local cert if it doesn't exist
		if [ ! -f "$CSRFILE" ]; then
			echo "CSR file not found, assuming self-signed and skipping."
			continue
		fi

		mkdir -p "$CHALLENGEDIR"

		"$ROOTPWD/acme_tiny" \
			--account-key "$KEYFILE" \
			--csr "$CSRFILE" \
			--acme-dir "$CHALLENGEDIR" \
			>"$TMPOUT"

		# If TMPOUT is empty, something failed.
		# Do not modify the current fullchain.
		if [ ! -s "$TMPOUT" ]; then
			echo "Error: $TMPOUT is empty - please see previous output for details.\nContinuing to next domain..."
			rm -f "$TMPOUT"
			continue
		fi

		# check if exists
		if [ -f "$FULLCHAIN" ]; then
			mv $FULLCHAIN "$FULLCHAIN.old"
		fi

		mv "$TMPOUT" "$FULLCHAIN"

		echo "Renewed certificate for $DOMAIN"
	} || {
		echo "Error processing $SITEROOT — skipping."
	}
done

sudo /usr/local/bin/nginx -s reload -c "$(pwd)/local/nginx.conf"
echo "Nginx reloaded."
