#!/bin/bash
# ============================================================
#  ChromExt ProgiDev — Installateur macOS
#  par SAS GBonnaire — https://chromeext.progidev.net
# ============================================================

BASE_URL="https://chromeext.progidev.net"
EXT_BASE_DIR="$HOME/.chrome-extensions"

RED='\033[0;31m'
ORANGE='\033[0;33m'
GREEN='\033[0;32m'
BOLD='\033[1m'
NC='\033[0m'

echo ""
echo " =============================="
echo "    CHROMEXT PROGIDEV"
echo "    par SAS GBonnaire"
echo " =============================="
echo ""

# --- Nom du plugin ---
if [ -n "$1" ]; then
    PLUGIN_NAME="$1"
else
    read -rp " Nom du plugin (sur progidev) : " PLUGIN_NAME
fi
[ -z "$PLUGIN_NAME" ] && echo -e " ${RED}ERREUR : Nom du plugin requis.${NC}" && exit 1

UPDATE_URL="${BASE_URL}/${PLUGIN_NAME}/updates.xml"
XML_TMP=$(mktemp /tmp/${PLUGIN_NAME}_XXXXXX.xml)
EXT_DIR="${EXT_BASE_DIR}/${PLUGIN_NAME}"

echo ""
echo " ${PLUGIN_NAME} - Installation"
echo " =============================="
echo ""

# --- Téléchargement avec retry ---
download_file() {
    local url="$1" dest="$2" attempt=0
    while [ $attempt -lt 5 ]; do
        attempt=$((attempt + 1))
        curl -L -s -f -A "Mozilla/5.0" -o "$dest" "$url" && [ -s "$dest" ] && return 0
        [ $attempt -lt 5 ] && echo "       Tentative $attempt échouée, nouvel essai dans 3s..." && sleep 3
    done
    return 1
}

# --- [1/4] Lecture du updates.xml ---
echo "[1/4] Lecture de la dernière version disponible..."
if ! download_file "$UPDATE_URL" "$XML_TMP"; then
    echo -e " ${RED}ERREUR : Impossible de télécharger updates.xml${NC}"
    rm -f "$XML_TMP"; exit 1
fi

if command -v xmllint &>/dev/null; then
    EXT_ID=$(xmllint   --xpath 'string(//*[local-name()="app"]/@appid)'            "$XML_TMP" 2>/dev/null)
    VERSION=$(xmllint  --xpath 'string(//*[local-name()="updatecheck"]/@version)'  "$XML_TMP" 2>/dev/null)
    CODEBASE=$(xmllint --xpath 'string(//*[local-name()="updatecheck"]/@codebase)' "$XML_TMP" 2>/dev/null)
else
    EXT_ID=$(python3 - "$XML_TMP" <<'PY'
import sys, xml.etree.ElementTree as ET
r = ET.parse(sys.argv[1]).getroot()
n = r.find('.//{*}app')
print(n.get('appid','') if n is not None else '')
PY
)
    VERSION=$(python3 - "$XML_TMP" <<'PY'
import sys, xml.etree.ElementTree as ET
r = ET.parse(sys.argv[1]).getroot()
n = r.find('.//{*}updatecheck')
print(n.get('version','') if n is not None else '')
PY
)
    CODEBASE=$(python3 - "$XML_TMP" <<'PY'
import sys, xml.etree.ElementTree as ET
r = ET.parse(sys.argv[1]).getroot()
n = r.find('.//{*}updatecheck')
print(n.get('codebase','') if n is not None else '')
PY
)
fi
rm -f "$XML_TMP"

[ -z "$EXT_ID" ] || [ -z "$VERSION" ] && \
    echo -e " ${RED}ERREUR : Impossible de parser updates.xml.${NC}" && exit 1
[[ "$CODEBASE" != http* ]] && CODEBASE="https://$CODEBASE"
ZIP_URL="${CODEBASE%.crx}.zip"

echo "       Extension : $EXT_ID"
echo "       Version   : $VERSION"

# Nettoyage des anciens artefacts (tentatives précédentes)
EXT_OLD_JSON="$HOME/Library/Application Support/Google/Chrome/External Extensions/${EXT_ID}.json"
[ -f "$EXT_OLD_JSON" ] && rm -f "$EXT_OLD_JSON" && echo "       Nettoyage : ancien External Extensions JSON supprimé"

# --- [2/4] Téléchargement et extraction du ZIP ---
INSTALLED_VERSION=""
[ -f "$EXT_DIR/.version" ] && INSTALLED_VERSION=$(cat "$EXT_DIR/.version")

if [ "$INSTALLED_VERSION" = "$VERSION" ] && [ -f "$EXT_DIR/manifest.json" ]; then
    echo ""
    echo "       Déjà installé en v${VERSION}."
else
    echo ""
    echo "[2/4] Téléchargement et extraction du plugin v${VERSION}..."

    ZIP_TMP=$(mktemp /tmp/${PLUGIN_NAME}_XXXXXX.zip)
    if ! download_file "$ZIP_URL" "$ZIP_TMP"; then
        echo -e " ${RED}ERREUR : Téléchargement du ZIP échoué.${NC}"
        echo " Vérifiez que le fichier existe : $ZIP_URL"
        rm -f "$ZIP_TMP"; exit 1
    fi

    rm -rf "$EXT_DIR" && mkdir -p "$EXT_DIR"
    TMP_EXTRACT=$(mktemp -d)
    unzip -q "$ZIP_TMP" -d "$TMP_EXTRACT" || {
        echo -e " ${RED}ERREUR : Extraction échouée.${NC}"
        rm -f "$ZIP_TMP"; rm -rf "$TMP_EXTRACT"; exit 1
    }
    rm -f "$ZIP_TMP"

    TOP_ITEMS=$(ls -1 "$TMP_EXTRACT" | grep -v '__MACOSX' | wc -l | tr -d ' ')
    FIRST_ITEM=$(ls -1 "$TMP_EXTRACT" | grep -v '__MACOSX' | head -1)
    if [ "$TOP_ITEMS" -eq 1 ] && [ -d "$TMP_EXTRACT/$FIRST_ITEM" ]; then
        cp -r "$TMP_EXTRACT/$FIRST_ITEM"/. "$EXT_DIR/"
    else
        cp -r "$TMP_EXTRACT"/. "$EXT_DIR/"
    fi
    rm -rf "$TMP_EXTRACT"

    [ ! -f "$EXT_DIR/manifest.json" ] && \
        echo -e " ${RED}ERREUR : manifest.json introuvable dans le ZIP.${NC}" && exit 1

    echo "$VERSION" > "$EXT_DIR/.version"
    echo "       OK — $EXT_DIR"
fi

# --- [3/4] Sélection du profil Chrome ---
echo ""
echo "[3/4] Détection des profils Chrome..."

PROFILES_RAW=$(python3 - <<'PY'
import json, os

chrome_dir = os.path.expanduser('~/Library/Application Support/Google/Chrome')
info_cache = {}
try:
    with open(os.path.join(chrome_dir, 'Local State'), encoding='utf-8') as f:
        info_cache = json.load(f).get('profile', {}).get('info_cache', {})
except Exception:
    pass

candidates = ['Default'] + [f'Profile {i}' for i in range(1, 20)]
for d in candidates:
    if not os.path.exists(os.path.join(chrome_dir, d, 'Preferences')):
        continue
    info  = info_cache.get(d, {})
    name  = (info.get('gaia_name') or info.get('name') or d).strip()
    email = info.get('user_name', '').strip()
    label = f'{name}  ({email})' if email else (name or d)
    print(f'{d}|{label}')
PY
)

if [ -z "$PROFILES_RAW" ]; then
    echo -e " ${RED}ERREUR : Aucun profil Chrome trouvé.${NC}"
    exit 1
fi

PROFILE_COUNT=$(echo "$PROFILES_RAW" | wc -l | tr -d ' ')

if [ "$PROFILE_COUNT" -eq 1 ]; then
    SELECTED_PROFILE_DIR=$(echo "$PROFILES_RAW" | cut -d'|' -f1)
    SELECTED_PROFILE_NAME=$(echo "$PROFILES_RAW" | cut -d'|' -f2)
    echo "       Profil unique : $SELECTED_PROFILE_NAME"
else
    echo ""
    echo " Profils Chrome disponibles :"
    echo ""
    i=1
    while IFS='|' read -r dir_name profile_name; do
        echo "   $i. $profile_name"
        i=$((i + 1))
    done <<< "$PROFILES_RAW"
    echo ""
    while true; do
        read -rp " Choisissez un profil [1-${PROFILE_COUNT}] : " CHOICE
        [[ "$CHOICE" =~ ^[0-9]+$ ]] && [ "$CHOICE" -ge 1 ] && [ "$CHOICE" -le "$PROFILE_COUNT" ] && break
        echo -e " ${RED}Choix invalide.${NC}"
    done
    SELECTED_PROFILE_DIR=$(echo "$PROFILES_RAW" | sed -n "${CHOICE}p" | cut -d'|' -f1)
    SELECTED_PROFILE_NAME=$(echo "$PROFILES_RAW" | sed -n "${CHOICE}p" | cut -d'|' -f2)
    echo "       Profil sélectionné : $SELECTED_PROFILE_NAME"
fi

# --- [4/4] Ouverture Chrome + Finder ---
echo ""
echo "[4/4] Ouverture de Chrome et du Finder..."

CHROME_APP="/Applications/Google Chrome.app"
[ ! -d "$CHROME_APP" ] && CHROME_APP="$HOME/Applications/Google Chrome.app"
[ ! -d "$CHROME_APP" ] && echo -e " ${RED}ERREUR : Google Chrome introuvable.${NC}" && exit 1

CHROME_BINARY="$CHROME_APP/Contents/MacOS/Google Chrome"
"$CHROME_BINARY" --profile-directory="$SELECTED_PROFILE_DIR" "chrome://extensions" &
sleep 2
open "$EXT_BASE_DIR"

echo ""
echo " =================================="
echo -e "  ${GREEN}${BOLD}${PLUGIN_NAME} v${VERSION} — prêt à charger${NC}"
echo " =================================="
echo ""
echo "  Dans Chrome (chrome://extensions) :"
echo ""
echo -e "  ${BOLD}1.${NC} Activez « Mode Développeur »"
echo "     (interrupteur en haut à droite)"
echo ""
echo -e "  ${BOLD}2.${NC} Depuis le Finder, glissez-déposez"
echo "     le dossier suivant sur la page Chrome :"
echo -e "     ${BOLD}${PLUGIN_NAME}${NC}"
echo ""
echo -e "  ${ORANGE}→ Action unique : Chrome mémorise l'extension${NC}"
echo -e "  ${ORANGE}  et la recharge à chaque démarrage.${NC}"
echo " =================================="
echo ""
