#!/bin/bash

SERVER_IP="79.97.5.12"
CERT_NAME="ssl-cert.crt"
TEMP_CERT="/tmp/$CERT_NAME"

echo "1. Downloading certificate from the server..."
# Download using curl, telling it to temporarily ignore the self-signed warning (-k)
curl -k -s "https://$SERVER_IP/$CERT_NAME" -o "$TEMP_CERT"

if [ ! -f "$TEMP_CERT" ] || [ ! -s "$TEMP_CERT" ]; then
    echo "ERROR: Failed to download the certificate. Check your server connection or IP."
    exit 1
fi

# Detect Operating System
OS_TYPE="$(uname)"

echo "2. Installing certificate (Admin password may be required)..."

if [ "$OS_TYPE" == "Darwin" ]; then
    # --- macOS Configuration ---
    echo "Detected macOS..."
    # Adds to the system keychain and explicitly sets trust settings for SSL/TLS
    sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$TEMP_CERT"
    
elif [ -f /etc/debian_version ]; then
    # --- Ubuntu / Debian / Mint ---
    echo "Detected Ubuntu/Debian layout..."
    sudo cp "$TEMP_CERT" /usr/local/share/ca-certificates/server-selfsigned.crt
    sudo update-ca-certificates

elif [ -f /etc/redhat-release ] || [ -f /etc/system-release ]; then
    # --- CentOS / RHEL / Rocky Linux / Fedora ---
    echo "Detected RedHat/CentOS layout..."
    sudo cp "$TEMP_CERT" /etc/pki/ca-trust/source/anchors/server-selfsigned.crt
    sudo update-ca-trust extract

else
    echo "ERROR: Unsupported Linux distribution. Please install manually."
    rm -f "$TEMP_CERT"
    exit 1
fi

# Cleanup
rm -f "$TEMP_CERT"

echo "############################################################"
echo "SUCCESS: Certificate installed!"
echo "Please COMPLETELY RESTART your web browser (Chrome/Firefox)."
echo "############################################################"
