#!/bin/bash

# File containing domain details
DOMAIN_FILE="/opt/domain.txt"
CERT_DIR="/opt/amol"
emailFrom="noreply@naaptol.com"
emailTo="amol.arote@naaptol.com"
smtp="192.168.58.7"

# Read the domain file and validate/install certificates
while IFS=, read -r domain email; do
  echo "Validating and installing certificate for $domain with email $email"

  # Validate the domain and install the certificate
  ~/.acme.sh/acme.sh --renew -d $domain --install-cert -d $domain \
  --cert-file $CERT_DIR/$domain.pem \
  --key-file $CERT_DIR/$domain.key \
  --fullchain-file $CERT_DIR/$domain.fullchain.pem \
  --reloadcmd "echo 'Certificate installed'"

  # Create a tarball of the certificate files
  tar -czvf $domain-certificates.tar.gz -C $CERT_DIR $domain.pem $domain.key $domain.fullchain.pem

  # Email the certificate files
  echo "Please find the certificate files for $domain attached." | mailx -v -s "Certificate Files for $domain" -a $domain-certificates.tar.gz \
  -S smtp=$smtp -r $emailFrom $emailTo

  # Clean up the tarball
  rm $domain-certificates.tar.gz
done < $DOMAIN_FILE

