# ============================================================
# PrestaShop 9+
# Recherche de l'archive exacte dans le référentiel officiel
# ============================================================

if [ "$PS_MAJOR" -ge 9 ]; then

    echo
    echo "Recherche de la distribution correspondant à $PS_VERSION..."

    METADATA_URL="https://raw.githubusercontent.com/PrestaShop/prestashop-flashlight/main/prestashop-versions.json"

    if ! wget \
        --https-only \
        --timeout=30 \
        --tries=2 \
        -q \
        "$METADATA_URL" \
        -O "$VERSIONS_FILE"
    then
        echo "Erreur : impossible de récupérer le référentiel PrestaShop."
        exit 1
    fi

    # Recherche des distributions correspondant exactement
    # à la version du coeur.
    #
    # Exemple :
    #   9.1.5 -> 9.1.5-5.0
    #
    # Les alpha / beta / rc sont ignorées.
    #
    # awk est utilisé ici pour éviter les expressions grep
    # fragiles avec les tirets dans les classes de caractères.

    MATCH_LINE="$(
        awk \
            -v prefix="\"${PS_VERSION}-" \
            '
            index($0, prefix) && $0 !~ /-(alpha|beta|rc)/ {
                print
            }
            ' \
            "$VERSIONS_FILE" \
        | sort -V \
        | tail -n 1
    )"

    if [ -z "$MATCH_LINE" ]; then

        echo
        echo "Erreur : aucune distribution stable trouvée pour PrestaShop $PS_VERSION."
        exit 1

    fi

    # Exemple de ligne :
    #
    # "9.1.5-5.0": "https://assets.../prestashop_edition_basic_version_9.1.5-5.0.zip",

    EDITION_VERSION="$(
        printf '%s\n' "$MATCH_LINE" |
        awk -F'"' '{print $2}'
    )"

    DOWNLOAD_URL="$(
        printf '%s\n' "$MATCH_LINE" |
        awk -F'"' '{print $4}'
    )"

    if [ -z "$EDITION_VERSION" ] || [ -z "$DOWNLOAD_URL" ]; then

        echo "Erreur : impossible d'analyser les informations de distribution."
        exit 1

    fi

    echo "Distribution détectée : $EDITION_VERSION"
    echo "Archive détectée : $DOWNLOAD_URL"


# ============================================================
# PrestaShop <= 8
# ============================================================

else

    DOWNLOAD_URL="https://github.com/PrestaShop/PrestaShop/releases/download/${PS_VERSION}/prestashop_${PS_VERSION}.zip"

fi