#!/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"
  local domain="$4"

  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 DOMAIN in $DOMAINS; do
  # Create a directory for the domain
  WEBROOT="$WEBROOT_BASE/$DOMAIN"
  mkdir -p "$WEBROOT/.well-known/acme-challenge"

  # Generate the challenge files
  ~/.acme.sh/acme.sh --issue --debug 2 -d $DOMAIN --webroot $WEBROOT --server https://acme-v02.api.letsencrypt.org/directory --force --config-home $ACME_HOME &

  # PID of the acme.sh process
  ACME_PID=$!

  # Wait for a few seconds to ensure challenge files are created
  sleep 10

  # Kill the acme.sh process to prevent verification
  kill $ACME_PID

  echo "Challenge files have been created in $WEBROOT/.well-known/acme-challenge/ for $DOMAIN"

  # Send email with challenge files
  for FILE in $WEBROOT/.well-known/acme-challenge/*; do
    send_email "Challenge File for $DOMAIN" "Please find the challenge file for $DOMAIN attached." "$FILE" "$DOMAIN"
  done
done

echo "Challenge files have been sent via email."

