#!/bin/bash

set -euo pipefail

# ============================================================
# Joomla.sh
#
# Réinjection des fichiers coeur Joomla depuis le package
# officiel correspondant exactement à la version installée.
#
# Le script doit être placé à la racine du site Joomla.
# Il se supprime uniquement si toute l'opération réussit.
# ============================================================


# ============================================================
# Se placer dans le dossier du script
# ============================================================

SCRIPT_PATH="$(readlink -f "$0")"
ROOT_DIR="$(dirname "$SCRIPT_PATH")"

cd "$ROOT_DIR"

echo "============================================"
echo " Réinjection des fichiers coeur Joomla"
echo "============================================"
echo
echo "Racine du site : $ROOT_DIR"


# ============================================================
# Vérification Joomla
# ============================================================

if [ ! -f "configuration.php" ]; then
    echo "Erreur : configuration.php introuvable."
    echo "Le script doit être placé à la racine du site Joomla."
    exit 1
fi

if [ ! -d "administrator" ]; then
    echo "Erreur : dossier administrator introuvable."
    exit 1
fi


# ============================================================
# Vérification des commandes nécessaires
# ============================================================

for CMD in wget unzip rsync sed grep stat; do

    if ! command -v "$CMD" >/dev/null 2>&1; then
        echo "Erreur : commande '$CMD' introuvable."
        exit 1
    fi

done


# ============================================================
# Détection version Joomla
#
# Peut être forcée avec :
#
# JOOMLA_VERSION=5.4.9 ./Joomla.sh
# ============================================================

JOOMLA_VERSION="${JOOMLA_VERSION:-}"


# ------------------------------------------------------------
# Méthode 1 : manifeste Joomla
# ------------------------------------------------------------

if [ -z "$JOOMLA_VERSION" ] && \
   [ -f "administrator/manifests/files/joomla.xml" ]; then

    JOOMLA_VERSION=$(
        sed -n \
            's:.*<version>[[:space:]]*\([^<]*\)[[:space:]]*</version>.*:\1:p' \
            administrator/manifests/files/joomla.xml \
        | head -n 1 \
        | tr -d '[:space:]'
    )

fi


# ------------------------------------------------------------
# Méthode 2 : libraries/src/Version.php
# Fallback notamment utile si le manifeste est absent/corrompu
# ------------------------------------------------------------

if [ -z "$JOOMLA_VERSION" ] && \
   [ -f "libraries/src/Version.php" ]; then

    VERSION_FILE="libraries/src/Version.php"

    MAJOR=$(
        sed -nE \
            "s/^[[:space:]]*(public[[:space:]]+)?const[[:space:]]+MAJOR_VERSION[[:space:]]*=[[:space:]]*'?([0-9]+)'?[[:space:]]*;.*/\2/p" \
            "$VERSION_FILE" \
        | head -n 1
    )

    MINOR=$(
        sed -nE \
            "s/^[[:space:]]*(public[[:space:]]+)?const[[:space:]]+MINOR_VERSION[[:space:]]*=[[:space:]]*'?([0-9]+)'?[[:space:]]*;.*/\2/p" \
            "$VERSION_FILE" \
        | head -n 1
    )

    PATCH=$(
        sed -nE \
            "s/^[[:space:]]*(public[[:space:]]+)?const[[:space:]]+PATCH_VERSION[[:space:]]*=[[:space:]]*'?([0-9]+)'?[[:space:]]*;.*/\2/p" \
            "$VERSION_FILE" \
        | head -n 1
    )

    if [ -n "$MAJOR" ] && \
       [ -n "$MINOR" ] && \
       [ -n "$PATCH" ]; then

        JOOMLA_VERSION="${MAJOR}.${MINOR}.${PATCH}"

    fi

fi


# ============================================================
# Validation version
# ============================================================

if [ -z "$JOOMLA_VERSION" ]; then

    echo
    echo "Erreur : impossible de détecter la version Joomla."
    echo
    echo "La version peut être forcée manuellement :"
    echo
    echo "JOOMLA_VERSION=5.4.9 ./Joomla.sh"

    exit 1

fi


# Sécurité : uniquement x.y.z
if ! echo "$JOOMLA_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then

    echo "Erreur : version Joomla invalide : $JOOMLA_VERSION"
    exit 1

fi


JOOMLA_MAJOR="${JOOMLA_VERSION%%.*}"

echo
echo "Version détectée : Joomla $JOOMLA_VERSION"


# ============================================================
# Variables
# ============================================================

ARCHIVE=".joomla_${JOOMLA_VERSION}.zip"
TMP_DIR=".joomla-reinject-$$"
SOURCE_DIR="$TMP_DIR/source"

PACKAGE="Joomla_${JOOMLA_VERSION}-Stable-Full_Package.zip"

GITHUB_URL="https://github.com/joomla/joomla-cms/releases/download/${JOOMLA_VERSION}/${PACKAGE}"

VERSION_PATH="${JOOMLA_VERSION//./-}"

JOOMLA_URL="https://downloads.joomla.org/cms/joomla${JOOMLA_MAJOR}/${VERSION_PATH}/${PACKAGE}"


# ============================================================
# Nettoyage automatique des fichiers temporaires
# ============================================================

cleanup() {

    rm -rf -- "$ARCHIVE" "$TMP_DIR"

}

trap cleanup EXIT


mkdir -p "$SOURCE_DIR"


# ============================================================
# Détection propriétaire du site
# ============================================================

SITE_USER="$(stat -c "%U" "$ROOT_DIR")"
SITE_GROUP="$(stat -c "%G" "$ROOT_DIR")"

echo "Propriétaire : $SITE_USER:$SITE_GROUP"


# ============================================================
# Téléchargement
# ============================================================

echo
echo "Téléchargement du package Joomla $JOOMLA_VERSION..."


# ------------------------------------------------------------
# Source 1 : repository officiel Joomla sur GitHub
# ------------------------------------------------------------

if wget \
    --https-only \
    --timeout=30 \
    --tries=2 \
    -q \
    --show-progress \
    "$GITHUB_URL" \
    -O "$ARCHIVE"
then

    echo "Téléchargement GitHub OK."

else

    echo
    echo "Échec du téléchargement GitHub."
    echo "Tentative depuis downloads.joomla.org..."

    rm -f "$ARCHIVE"

    if ! wget \
        --https-only \
        --timeout=30 \
        --tries=2 \
        -q \
        --show-progress \
        "$JOOMLA_URL" \
        -O "$ARCHIVE"
    then

        echo
        echo "Erreur : impossible de télécharger Joomla $JOOMLA_VERSION."
        echo
        echo "URLs testées :"
        echo "$GITHUB_URL"
        echo "$JOOMLA_URL"

        exit 1

    fi

fi


# ============================================================
# Contrôle archive
# ============================================================

if [ ! -s "$ARCHIVE" ]; then

    echo "Erreur : archive vide."
    exit 1

fi


if ! unzip -tq "$ARCHIVE" >/dev/null 2>&1; then

    echo "Erreur : archive ZIP invalide ou corrompue."
    exit 1

fi


# ============================================================
# Extraction
# ============================================================

echo
echo "Extraction du package..."

unzip -q "$ARCHIVE" -d "$SOURCE_DIR"


# ============================================================
# Vérification du contenu extrait
# ============================================================

if [ ! -f "$SOURCE_DIR/index.php" ]; then

    echo "Erreur : index.php absent du package Joomla."
    exit 1

fi


if [ ! -d "$SOURCE_DIR/administrator" ]; then

    echo "Erreur : dossier administrator absent du package Joomla."
    exit 1

fi


if [ ! -d "$SOURCE_DIR/libraries" ]; then

    echo "Erreur : dossier libraries absent du package Joomla."
    exit 1

fi


# ============================================================
# Vérification que le package téléchargé correspond bien
# à la version demandée
# ============================================================

PACKAGE_VERSION=""

if [ -f "$SOURCE_DIR/administrator/manifests/files/joomla.xml" ]; then

    PACKAGE_VERSION=$(
        sed -n \
            's:.*<version>[[:space:]]*\([^<]*\)[[:space:]]*</version>.*:\1:p' \
            "$SOURCE_DIR/administrator/manifests/files/joomla.xml" \
        | head -n 1 \
        | tr -d '[:space:]'
    )

fi


if [ -n "$PACKAGE_VERSION" ] && \
   [ "$PACKAGE_VERSION" != "$JOOMLA_VERSION" ]; then

    echo
    echo "ERREUR : version incorrecte dans le package."
    echo
    echo "Version installée : $JOOMLA_VERSION"
    echo "Version téléchargée : $PACKAGE_VERSION"

    exit 1

fi


# ============================================================
# Attribution des fichiers extraits au propriétaire du site
#
# Important lorsque le script est exécuté en root depuis WHM.
# ============================================================

if [ "$(id -u)" -eq 0 ]; then

    echo
    echo "Attribution des fichiers temporaires à $SITE_USER:$SITE_GROUP..."

    chown -R "$SITE_USER:$SITE_GROUP" "$SOURCE_DIR"

fi


# ============================================================
# Réinjection
#
# IMPORTANT :
#
# On NE FAIT PAS de --delete.
#
# Cela permet de conserver :
# - composants tiers
# - modules tiers
# - plugins tiers
# - templates tiers
# - fichiers propres au client
#
# Les fichiers Joomla présents dans le package officiel sont
# en revanche remplacés si leur contenu diffère.
# ============================================================

echo
echo "Réinjection des fichiers Joomla..."


rsync \
    -a \
    --checksum \
    --itemize-changes \
    \
    --exclude='/configuration.php' \
    \
    --exclude='/.htaccess' \
    --exclude='/.htpasswd' \
    --exclude='/.user.ini' \
    --exclude='/php.ini' \
    --exclude='/web.config' \
    --exclude='/robots.txt' \
    \
    --exclude='/images/' \
    \
    --exclude='/cache/' \
    --exclude='/administrator/cache/' \
    --exclude='/administrator/logs/' \
    --exclude='/logs/' \
    --exclude='/tmp/' \
    \
    --exclude='/installation/' \
    \
    "$SOURCE_DIR/" \
    "$ROOT_DIR/"


# ============================================================
# Nettoyage cache Joomla
# ============================================================

echo
echo "Nettoyage des caches..."


if [ -d "$ROOT_DIR/cache" ]; then

    find "$ROOT_DIR/cache" \
        -mindepth 1 \
        ! -name 'index.html' \
        ! -name 'index.htm' \
        -delete 2>/dev/null || true

fi


if [ -d "$ROOT_DIR/administrator/cache" ]; then

    find "$ROOT_DIR/administrator/cache" \
        -mindepth 1 \
        ! -name 'index.html' \
        ! -name 'index.htm' \
        -delete 2>/dev/null || true

fi


# ============================================================
# Correction propriétaire
#
# On ne fait volontairement PAS :
#
# chown -R USER:USER .
#
# pour éviter de modifier inutilement toute l'arborescence.
# Les fichiers extraits ont déjà été attribués au propriétaire
# avant rsync.
# ============================================================


# ============================================================
# Fin
# ============================================================

echo
echo "============================================"
echo " Réinjection Joomla $JOOMLA_VERSION OK"
echo "============================================"
echo
echo "Configuration conservée : configuration.php"
echo "Extensions tierces conservées."
echo "Templates tiers conservés."
echo "Images/uploads conservés."
echo


# ============================================================
# Auto-suppression
#
# Cette ligne n'est atteinte que si toutes les opérations
# précédentes se sont correctement terminées.
# ============================================================

rm -f -- "$SCRIPT_PATH"

exit 0