#!/bin/bash

# Set the starting directory
START_DIR="/usr/syno/etc/letsencrypt/account"

# Iterate over each subdirectory in the starting directory
for dir in "$START_DIR"/*/; do
    # Check if the 'info.json' file exists in this subdirectory
    if [[ -f "${dir}info.json" ]]; then
        # Store the name of the subdirectory in a variable
        first_dir_with_info_json="$dir"
        # Exit the loop after finding the first matching subdirectory
        break
    fi
done

cd /usr/syno/etc/certificate/_archive/

# Display the name of the subdirectory, if found
if [[ -n $first_dir_with_info_json ]]; then
	account=$(basename "$first_dir_with_info_json")
    echo "First subdirectory containing info.json: $account"

    # Set the starting directory
    START_DIR="./"

    # Iterate over each directory in the starting directory
    find "$START_DIR" -type d | while read -r dir
    do
        # Check if the 'cert.pem' file exists in this directory
        if [[ -f "$dir/cert.pem" ]]; then
            # Display the name of the directory
			echo "processing ".$dir

            # Use jq to extract the display_name of the node TIXCA0
            node=$(basename "$dir")
            display_name=$(cat "./INFO" | jq -r --arg node "$node" '.[$node].services[0].display_name')

            # Test if the string contains ":80"
            if [[ $display_name == *":80"* ]]; then
                # Extract the value preceding ":80"
                website="${display_name%%:80*}"
                echo "The key $node is for the website $website"
				
				# Create renew JSON 
				json_content=$(cat <<-EOF
				{
					"account" : "/usr/syno/etc/letsencrypt/account/$account",
					"domains" : "$website",
					"server" : "https://acme-v02.api.letsencrypt.org/directory",
					"version" : 2
				}
				EOF
				)

				# Write JSON content into renew.json in the target folder
				echo "$json_content" > "${dir}/renew.json"
			else
				echo $dir." couldn't be processed"
            fi
			echo "------------------------------------------"
        fi
    done

else
    echo "No subdirectory containing info.json was found."
fi
