#!/bin/bash
set -euo pipefail
echo "Mkcert Installation: # $0" 1>&2
echo

sudo apt-get -y install ca-certificates libnss3-tools
ROOT="$(pwd)"

get_primary_ip() {
  # Test eth0 first
  if ip -4 addr show dev eth0 >/dev/null 2>&1; then
    ip -4 -o addr show dev eth0 | awk '{print $4}' | cut -d/ -f1 | head -n1
  else
    ip -4 -o addr show scope global | awk '{print $4 " " $2}' | grep -v lo | head -n1 | cut -d/ -f1
  fi
}

IP="$(get_primary_ip)"
CERTS="${ROOT}/certs"

DOMAIN_SERVER="relay.local"
MKCERT_VERSION="v1.4.4"
LOCAL_DOMAINS="127.0.0.1 localhost $IP ${DOMAIN_SERVER}"

# --- mkcert installation ---
echo "==== mkcert installation ===="
# Déduire URL binaire selon architecture
ARCH="$(uname -m)"
case "$ARCH" in
  aarch64|arm64) ARCH_TAG="linux-arm64" ;;
  armv7l|armv7) ARCH_TAG="linux-arm" ;;
  x86_64) ARCH_TAG="linux-amd64" ;;
  *) ARCH_TAG="linux-amd64" ;;
esac

MKCERT_BINARY_NAME="mkcert-${MKCERT_VERSION}-${ARCH_TAG}"

#https://github.com/FiloSottile/mkcert/releases/download/v1.4.4/mkcert-v1.4.4-linux-arm64
MKCERT_URL="https://github.com/FiloSottile/mkcert/releases/download/${MKCERT_VERSION}/${MKCERT_BINARY_NAME}"
echo "Téléchargement: $MKCERT_URL"
wget "$MKCERT_URL"
sudo mv "$MKCERT_BINARY_NAME" /usr/local/bin/mkcert
chmod +x /usr/local/bin/mkcert

# Installer racine mkcert si nécessaire
if ! mkcert -CAROOT >/dev/null 2>&1; then
  mkcert -install || true
fi

echo "==== Génération des certificats pour: $LOCAL_DOMAINS ===="
mkdir -p "$CERTS"
pushd "$CERTS" >/dev/null
# mkcert supporte listes d'arguments ; on passe en tant que mots
# Note: si trop long, mkcert créera wildcard/local CA selon besoin
mkcert -cert-file "${DOMAIN_SERVER}.pem" -key-file "${DOMAIN_SERVER}-key.pem" $LOCAL_DOMAINS
popd >/dev/null

echo "==== Copier certificat racine local pour navigateur ===="
LOCAL_CERTS_PATH="$HOME/.local/share/mkcert/rootCA.pem"

if [ -f "$LOCAL_CERTS_PATH" ]; then
  cp "$LOCAL_CERTS_PATH" "$CERTS/${DOMAIN_SERVER}-root-cert.pem"
  echo "Certificat copié: $CERTS/${DOMAIN_SERVER}-root-cert.pem"
else
  echo "Root CA mkcert introuvable à $LOCAL_CERTS_PATH"
fi

echo "==== Mise à jour /etc/hosts ===="
# On ajoute une ligne unique contenant IP puis tous les domaines
HOSTS_LINE="$IP $DOMAIN_SERVER"
if ! grep -qE "^${IP}[[:space:]]+${DOMAIN_SERVER}(\s|$)" /etc/hosts; then
  printf "%s\n" "$HOSTS_LINE" | sudo tee -a /etc/hosts >/dev/null
  echo "/etc/hosts mis à jour"
else
  echo "/etc/hosts contient déjà une entrée pour $IP"
fi





