#!/bin/bash

# This script installs the local CA certificate on Ubuntu systems to avoid
# certificate warnings in browsers when accessing internal cloud services.

# Set up error handling
set -e

# Define colors for better readability
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

CA_DIR="/home/payne/repos/cloud.payne.io-setup/ca"
CA_FILE="$CA_DIR/ca.crt"
TARGET_DIR="/usr/local/share/ca-certificates"
TARGET_FILE="cloud-payne-local-ca.crt"

echo -e "${BLUE}=== Installing Local CA Certificate on Ubuntu ===${NC}"
echo

# Check if CA file exists
if [ ! -f "$CA_FILE" ]; then
    echo -e "${RED}CA certificate not found at $CA_FILE${NC}"
    echo -e "${YELLOW}Please run the create-local-ca script first:${NC}"
    echo -e "${BLUE}./bin/create-local-ca${NC}"
    exit 1
fi

# Copy to the system certificate directory
echo -e "${YELLOW}Copying CA certificate to $TARGET_DIR/$TARGET_FILE...${NC}"
sudo cp "$CA_FILE" "$TARGET_DIR/$TARGET_FILE"

# Update the CA certificates
echo -e "${YELLOW}Updating system CA certificates...${NC}"
sudo update-ca-certificates

# Update browsers' CA store (optional, for Firefox)
if [ -d "$HOME/.mozilla" ]; then
    echo -e "${YELLOW}You may need to manually import the certificate in Firefox:${NC}"
    echo -e "1. Open Firefox"
    echo -e "2. Go to Preferences > Privacy & Security > Certificates"
    echo -e "3. Click 'View Certificates' > 'Authorities' tab"
    echo -e "4. Click 'Import' and select $CA_FILE"
    echo -e "5. Check 'Trust this CA to identify websites' and click OK"
fi

# Check popular browsers
if command -v google-chrome &> /dev/null; then
    echo -e "${YELLOW}For Chrome, the system-wide certificate should now be recognized${NC}"
    echo -e "${YELLOW}You may need to restart the browser${NC}"
fi

echo
echo -e "${GREEN}=== CA Certificate Installation Complete ===${NC}"
echo
echo -e "${YELLOW}System-wide CA certificate has been installed.${NC}"
echo -e "${YELLOW}You should now be able to access the Kubernetes Dashboard without certificate warnings:${NC}"
echo -e "${BLUE}https://kubernetes-dashboard.in.cloud.payne.io${NC}"
echo
echo -e "${YELLOW}If you still see certificate warnings, try:${NC}"
echo "1. Restart your browser"
echo "2. Clear your browser's cache and cookies"
echo "3. If using a non-standard browser, you may need to import the certificate manually"
echo