#!/bin/bash

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

# Function to install dependencies
install_dependencies() {
  if command -v yum &> /dev/null; then
    sudo yum install -y epel-release
    sudo yum install -y openssl curl jq mailx socat
  else
    echo "Package manager not found. Please install openssl, curl, jq, mailx, and socat manually."
    exit 1
  fi
}

# Install dependencies
install_dependencies

# Download and install acme.sh
curl https://get.acme.sh | sh

# Export the path to include acme.sh
export PATH="~/.acme.sh:$PATH"

# Register account with Let's Encrypt
~/.acme.sh/acme.sh --register-account -m $EMAIL_TO --server https://acme-v02.api.letsencrypt.org/directory

# Create the challenge directory
CHALLENGE_PATH="$WEBROOT/.well-known/acme-challenge"
mkdir -p $CHALLENGE_PATH

while IFS= read -r DOMAIN; do
  # Prepare for manual HTTP challenge
~/.acme.sh/acme.sh --issue --debug 2 -d $DOMAIN --webroot $WEBROOT --server https://acme-v02.api.letsencrypt.org/directory --force --staging &

 # ~/.acme.sh/acme.sh --issue --webroot $WEBROOT -d $DOMAIN --server https://acme-v02.api.letsencrypt.org/directory --yes-I-know-dns-manual-mode-enough-go-ahead-please --debug 2
  
  # Check if challenge files are created
  CHALLENGE_FILES=$(ls $CHALLENGE_PATH)
  if [ -z "$CHALLENGE_FILES" ]; then
    echo "No challenge files created for $DOMAIN"
    continue
  fi

  # Create email content
  EMAIL_SUBJECT="Challenge File for $DOMAIN"
  EMAIL_BODY="The challenge file for $DOMAIN has been generated. Please copy the following challenge file to the respective server path:\n\n$(cat $CHALLENGE_PATH/*)"

  # Send the email
  echo -e "$EMAIL_BODY" | mailx -s "$EMAIL_SUBJECT" -r "$EMAIL_FROM" -S smtp="$SMTP_SERVER" "$EMAIL_TO"

  # Clean up challenge directory
  rm -f $CHALLENGE_PATH/*
done < "$DOMAINS_FILE"

