#!/bin/bash

# Directory for storing GM certificates
cert_dir="/etc/pki/ca-trust/source/anchors"
national_ca_root_certs_dir="/etc/pki/ca-trust/source/national_ca_root_certs"
# Import all GM certificates under the path '/etc/pki/ca-trust/source/national_ca_root_certs'.
import_all_certificates() {
    cp -f "$national_ca_root_certs_dir"/* "$cert_dir"
    update_certificates
    echo "Successfully imported GM certificates."
}

# Import a GM certificate
import_a_certificate() {
    read -p "Please enter the path of the GM certificate to import: " cert_file
    if [ ! -f "$cert_file" ]; then
        echo "Error: Could not find specified certificate file."
        return 1
    fi

     # Check if the certificate is valid
    /usr/bin/openssl x509 -in "$cert_file" -noout -text > /dev/null
    if [ $? -ne 0 ]; then
        echo "Error: Invalid certificate file."
        return 1
    fi

    cp "$cert_file" "$cert_dir"
    update_certificates
    echo "Successfully imported GM certificate."
}

# View a list of installed GM certificates
view_certificates() {
    ls -l "$cert_dir"
}

view_cert_info() {
    read -p "Please enter the name of the GM certificate file to view the info: " cert_name
    if [ ! -f "$cert_dir/$cert_name" ]; then
        echo "Error: Please import the GM certificate or use the command 'openssl x509 -in <certificate_file_path> -text' to view the certificate information."
	return 1
    fi
    cert_info=$(/usr/bin/openssl x509 -in "$cert_dir/$cert_name" -text)
    echo "$cert_info"
}
	 
# Delete a GM certificate
delete_certificate() {
    read -p "Please enter the name of the GM certificate file to delete: " cert_name
    if [ -f "$cert_dir/$cert_name" ]; then
        rm "$cert_dir/$cert_name"
        update_certificates
        echo "Successfully deleted GM certificate."
    else
        echo "Error: Could not find specified certificate file."
        return 1
    fi
}


# Update the certificate store
update_certificates() {
    update-ca-trust
}

# Main menu
main_menu() {
    clear
    echo "=== GM Certificate Management ==="
    echo "1. Import all GM certificates under the path '/etc/pki/ca-trust/source/national_ca_root_certs'."
    echo "2. Import a GM certificate"
    echo "3. View installed GM certificates"
    echo "4. Delete a GM certificate"
    echo "5. View GM certioficate info"
    echo "0. Quit"
    echo "================================="
    read -p "Please enter your choice: " choice

    case $choice in
	1) import_all_certificates ;;
        2) import_a_certificate ;;
        3) view_certificates ;;
        4) delete_certificate ;;
        5) view_cert_info ;;
        0) exit ;;
        *) echo "Error: Invalid choice." ;;
    esac

    read -p "Press any key to return to the main menu." -n 1 -r
    main_menu
}

# Run the main menu
main_menu
