#!/bin/bash

# Set variables
DOCKER_CONTAINER="app"  # Replace with your Docker container name
CACERTS_PATH="/opt/java/openjdk/lib/security/cacerts"
TRUSTSTORE="truststore.jks"
TRUSTSTORE_PASSWORD="changeit"  # Default password for cacerts, change if needed
CERT_FOLDER="."  # Current directory for new certificates
TEMP_CACERTS="temp_cacerts"

# Function to copy cacerts from Docker container
copy_cacerts_from_docker() {
    echo "Copying cacerts from Docker container..."
    docker exec $DOCKER_CONTAINER cat $CACERTS_PATH > ./$TEMP_CACERTS
    if [ $? -eq 0 ] && [ -s "./$TEMP_CACERTS" ]; then
        echo "Successfully copied cacerts from Docker container."
    else
        echo "Failed to copy cacerts from Docker container."
        exit 1
    fi
}

# Function to create a new truststore from cacerts
create_new_truststore() {
    echo "Creating new truststore from cacerts..."
    if [ -f "./$TEMP_CACERTS" ]; then
        # Use keytool to create a new truststore
        keytool -importkeystore -srckeystore ./$TEMP_CACERTS -destkeystore "$TRUSTSTORE" -srcstorepass $TRUSTSTORE_PASSWORD -deststorepass $TRUSTSTORE_PASSWORD -noprompt
        if [ $? -eq 0 ]; then
            echo "Successfully created new truststore from cacerts."
            rm "./$TEMP_CACERTS"
        else
            echo "Failed to create new truststore from cacerts."
            exit 1
        fi
    else
        echo "Temporary cacerts file not found."
        exit 1
    fi
}

# Function to add a certificate to the truststore
add_cert_to_truststore() {
    local cert_file="$1"
    local alias="$(basename "$cert_file" | sed 's/\.[^.]*$//')"

    echo "Adding $cert_file to truststore..."
    keytool -importcert -file "$cert_file" -alias "$alias" -keystore "$TRUSTSTORE" -storepass "$TRUSTSTORE_PASSWORD" -noprompt

    if [ $? -eq 0 ]; then
        echo "Successfully added $cert_file to truststore."
    else
        echo "Failed to add $cert_file to truststore."
    fi
}

# Main execution
copy_cacerts_from_docker
create_new_truststore

# Loop through common certificate file extensions and add to truststore
echo "Starting certificate import loop..."
for ext in cer crt pem der; do
    echo "Checking for *.$ext files..."
    find "$CERT_FOLDER" -type f -name "*.$ext" -print0 | while IFS= read -r -d '' cert_file; do
        echo "Found file: $cert_file"
        add_cert_to_truststore "$cert_file"
    done
done

echo "Script completed. New truststore has been created with certificates from Docker container's cacerts and local directory."

echo "Restart service"

/usr/libexec/docker/cli-plugins/docker-compose restart app

echo "Service Started"

exit 0
