#!/bin/bash

ACME_HOME="/root/.acme.sh"
WEBROOT="/opt/data"
DOMAINS_FILE="/opt/domain.txt"
SSL_DIR="/opt/ssl"

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

# Validate the domain and issue the certificate without regenerating challenge files
~/.acme.sh/acme.sh --renew --debug 2 -d $DOMAIN --webroot $WEBROOT --server https://acme-v02.api.letsencrypt.org/directory --config-home $ACME_HOME --force

# Check if the certificate was generated successfully
if [ -f "$ACME_HOME/$DOMAIN/$DOMAIN.cer" ]; then
  # Create the SSL directory if it doesn't exist
  mkdir -p $SSL_DIR

  # Copy the certificate and key to the SSL directory
  cp "$ACME_HOME/$DOMAIN/$DOMAIN.cer" "$SSL_DIR/$DOMAIN.cer"
  cp "$ACME_HOME/$DOMAIN/$DOMAIN.key" "$SSL_DIR/$DOMAIN.key"
  cp "$ACME_HOME/$DOMAIN/ca.cer" "$SSL_DIR/ca.cer"

  echo "SSL certificate and key have been copied to $SSL_DIR"
else
  echo "Failed to generate the SSL certificate for $DOMAIN"
fi

