# SPDX-License-Identifier: Apache-2.0
set +x
YELLOW='\033[1;33m'
NC='\033[0m'

# Where to generate the certificates
TARGET_DIR="${1:-buildtools/certs}"

# Create directories
mkdir -p "$TARGET_DIR"
cd "$TARGET_DIR"

# Generate certificates
npx -y mkcert create-ca --organization GeoGirafe --key rootCA-key.pem --cert rootCA.pem
npx -y mkcert create-cert --ca-key rootCA-key.pem --ca-cert rootCA.pem --key app.localhost.key.pem --cert app.localhost.cert.pem --domains app.localhost localhost 127.0.0.1
chmod a+r app.localhost.* rootCA.pem
echo Certificate was created successfully.

# NOTE : THIS NEED SUDO! 
# DO WE REALLY WANT TO TRUST THE CERTS AT THE SYSTEM LEVEL DURING A DEFAULT INSTALLATION ?
# ==> Deactivate for the moment.
# Add root certificate to system trusted store
# echo Trusting development certificates at the system level
# sudo cp rootCA.pem /usr/local/share/ca-certificates/geogirafe-dev.crt
# sudo update-ca-certificates

# Trust root certificate in Firefox/Chrome user stores (NSS).
# No root rights needed.
# Importing into it requires certutil, which is optional: if it isn't installed
# we just skip this step and let the user trust the certificate manually in their browser.
if command -v certutil &> /dev/null; then
    echo Trusting development certificates in Chrome
    certutil -d sql:$HOME/.pki/nssdb -A -t TC -n "GeoGirafe LocalDevCert" -i rootCA.pem

    echo Trusting development certificates in Firefox
    FIREFOX_PROFILE=$(grep -E 'Path=' ~/.mozilla/firefox/profiles.ini 2> /dev/null | grep default-release | cut -d'=' -f2)
    if [ -n "$FIREFOX_PROFILE" ]; then
        certutil -d sql:$HOME/.mozilla/firefox/$FIREFOX_PROFILE -A -t "C,,C" -n "GeoGirafe LocalDevCert" -i rootCA.pem
    fi
    echo Certificate was added successfully.
    echo Please restart your browser to take it into account.
else
    echo -e "${YELLOW}certutil not found (part of the libnss3-tools package on Ubuntu/Debian).${NC}"
    echo -e "${YELLOW}Skipping automatic trust in Firefox/Chrome's certificate store.${NC}"
    echo -e "${YELLOW}Install libnss3-tools and re-run this script, or manually import $TARGET_DIR/rootCA.pem as a trusted authority in your browser settings.${NC}"
fi
