#!/bin/bash

# Set variables
DOMAIN="naaptolsalespartner.in"
WEBROOT="/opt/data/$DOMAIN"
ACME_HOME="/root/.acme.sh"

# Find the existing challenge file
CHALLENGE_DIR="$WEBROOT/.well-known/acme-challenge"
CHALLENGE_FILE=$(ls $CHALLENGE_DIR | head -n 1)

# Check if the challenge file exists
if [ -z "$CHALLENGE_FILE" ]; then
    echo "No challenge file found in $CHALLENGE_DIR"
    exit 1
fi

# Full path to the challenge file
CHALLENGE_PATH="$CHALLENGE_DIR/$CHALLENGE_FILE"

# Perform validation using the existing challenge file
/root/.acme.sh/acme.sh --renew --domain $DOMAIN --webroot $WEBROOT --server https://acme-v02.api.letsencrypt.org/directory --force --config-home $ACME_HOME

# Check if the validation was successful
if [ $? -eq 0 ]; then
    echo "Validation successful for $DOMAIN"

    # Generate the SSL certificate
    /root/.acme.sh/acme.sh --issue --domain $DOMAIN --webroot $WEBROOT --server https://acme-v02.api.letsencrypt.org/directory --force --config-home $ACME_HOME
    
    # Check if the SSL certificate generation was successful
    if [ $? -eq 0 ]; then
        echo "SSL certificate generated successfully for $DOMAIN"
    else
        echo "SSL certificate generation failed for $DOMAIN"
        exit 1
    fi

else
    echo "Validation failed for $DOMAIN"
    exit 1
fi

