#!/bin/bash

ACME_HOME="/root/.acme.sh"
WEBROOT_BASE="/opt/data"
DOMAINS_FILE="/opt/domain.txt"
EMAIL_FROM="noreply@naaptol.com"
EMAIL_TO="amol.arote@naaptol.com"
SMTP_SERVER="192.168.58.7"

# Function to send an email with a file attachment
send_email() {
  local subject="$1"
  local body="$2"
  local attachment="$3"

  echo "$body" | mailx -s "$subject" -r "$EMAIL_FROM" -a "$attachment" -S smtp="$SMTP_SERVER" "$EMAIL_TO"
}

# Read the domains from the domain file
DOMAINS=$(cat $DOMAINS_FILE)

# Loop through each domain for validation
for DOMAIN in $DOMAINS; do
  WEBROOT="$WEBROOT_BASE/$DOMAIN"
  
  echo "Starting validation for $DOMAIN using existing challenge files."

  # Validate the domain using the earlier generated challenge files
  ~/.acme.sh/acme.sh --renew --debug 2 -d $DOMAIN --webroot $WEBROOT --server https://acme-v02.api.letsencrypt.org/directory --force --config-home $ACME_HOME --log --test

  if [ $? -eq 0 ]; then
    echo "Validation successful for $DOMAIN"
    # Send email with the SSL certificate
    SSL_CERT="$ACME_HOME/$DOMAIN/fullchain.cer"
    send_email "SSL Certificate for $DOMAIN" "Please find the SSL certificate for $DOMAIN attached." "$SSL_CERT"
  else
    echo "Validation failed for $DOMAIN"
  fi
done

echo "SSL certificates have been sent via email."

