view host/renewSsl.sh @ 2078:ac991d32dea5 ssltesting

minor
author Violet7
date Tue, 09 Dec 2025 17:11:27 -0800
parents 385ab09fb2ca
children cdc9a31c6f71
line wrap: on
line source

#!/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")
    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"

    wc -c <$TMPOUT

    # If TMPOUT is empty, something failed.
    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."