# SPDX-License-Identifier: Apache-2.0
set +x

YELLOW='\033[1;33m'
NC='\033[0m'

# Ensure that openssl is installed (it ships by default on virtually every Linux distribution)
if ! command -v openssl &> /dev/null; then
    echo "openssl not found. Please install it first (e.g. 'sudo apt install openssl' on Ubuntu)"
    exit 1
fi

# Ask for sudo rights, it will be needed to trust the certificate
sudo -v

# Create directories
TARGET_DIR="${1:-buildtools/certs}"
mkdir -p "$TARGET_DIR"
cd "$TARGET_DIR"

DOMAINS="app.localhost,localhost"
IPS="127.0.0.1"

echo Generating development certificates

# Generate a local root CA (self-signed), reused across runs if it already exists
if [ ! -f rootCA.pem ] || [ ! -f rootCA-key.pem ]; then
    openssl genrsa -out rootCA-key.pem 4096 2> /dev/null
    openssl req -x509 -new -nodes -key rootCA-key.pem -sha256 -days 3650 \
        -subj "/O=GeoGirafe Development CA/CN=GeoGirafe Local Dev Root CA" \
        -addext "basicConstraints=critical,CA:TRUE" \
        -addext "keyUsage=critical,keyCertSign,cRLSign" \
        -out rootCA.pem
fi

# Build the Subject Alternative Name list for the leaf (server) certificate
SAN=$(echo "$DOMAINS" | tr ',' '\n' | sed 's/^/DNS:/' | paste -sd,)
SAN="$SAN,$(echo "$IPS" | tr ',' '\n' | sed 's/^/IP:/' | paste -sd,)"

# Generate the leaf certificate for the dev server, signed by the local root CA
openssl genrsa -out app.localhost.key.pem 2048 2> /dev/null
openssl req -new -key app.localhost.key.pem \
    -subj "/CN=app.localhost" \
    -out app.localhost.csr.pem

openssl x509 -req -in app.localhost.csr.pem \
    -CA rootCA.pem -CAkey rootCA-key.pem -CAcreateserial \
    -days 825 -sha256 \
    -extfile <(printf "subjectAltName=%s\nextendedKeyUsage=serverAuth" "$SAN") \
    -out app.localhost.cert.pem

rm -f app.localhost.csr.pem

sudo chmod a+r app.localhost.* rootCA.pem

# 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

# Firefox, and older Chrome builds, keep their own certificate store (NSS) instead of relying on
# the system one. 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
else
    echo -e "${YELLOW}certutil not found (optional, part of the libnss3-tools package on Ubuntu/Debian).${NC}"
    echo -e "${YELLOW}Skipping automatic trust in Firefox/Chrome's own 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

echo Certificate was added successfully.
echo Please restart your browser to take it into account.
