#!/bin/bash

set -e
cd "$1" || exit 1

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

    DOMAIN=$(basename "$SITEROOT")
    CSRFILE="$SITEROOT/$DOMAIN.csr"
    FULLCHAIN="$SITEROOT/fullchain.cer"
    CHALLENGEDIR="$SITEROOT/site/.well-known/acme-challenge"
    TMPOUT="/tmp/$DOMAIN.crt"
    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"

    # 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."
