#!/bin/bash
# =================================================================
# GESTIONNAIRE ODOO INTELLIGENT v2 (Installation ou Mise à jour)
# Système : Ubuntu 24.04 LTS — Odoo 19 CE (paquet nightly)
# Méthode IA&TIC — CC BY-SA 4.0 — https://netetic.fr/documentation/odoo-claude/installer
#
# v2 (2026-07-03) — corrections sur la v1 :
#   - Nginx : /websocket (Odoo 17+) remplace /longpolling, en-têtes Upgrade ajoutés
#   - odoo.conf : proxy_mode = True (obligatoire derrière reverse proxy)
#   - libssl1.1 : détection de la dernière version du dépôt + miroir de secours
#   - certbot : un seul certificat pour domaine + www
#   - MAJ auto nightly + reboot : désormais optionnelle (question posée, défaut Non)
# v2.1 (2026-07-04) — PDCA F: install réelle VPS dev.polytalents.fr (24.04 vierge) :
#   - addons_path : le odoo.conf du paquet nightly livre la ligne COMMENTÉE
#     (";addons_path = ...") — l'ancien sed remplaçait sans décommenter et le grep
#     d'idempotence était trompé par la ligne commentée → custom_addons jamais chargé.
#     Corrigé : sed décommente, grep exige une ligne active.
# v2.2 (2026-07-09) — robustesse reverse proxy (débogage VPS multisite netetic) :
#   - Nginx : ajout de « proxy_set_header Host $host; » au niveau server. Sans lui,
#     l'upstream reçoit Host = "odoo" (nom d'upstream) ; le routage multisite ne
#     tient alors que grâce à proxy_mode + X-Forwarded-Host. Avec cet en-tête, le
#     routage par domaine reste correct même si proxy_mode venait à être désactivé.
# =================================================================

MIRROR="https://netetic.fr/telechargements"   # miroir de secours des .deb

if [ "$EUID" -ne 0 ]; then
  echo "Erreur : Veuillez lancer ce script avec sudo."
  exit 1
fi

echo "--- Analyse du système en cours ---"

# --- ÉTAPE 1 : DÉPENDANCES ET POSTGRESQL ---
if ! command -v psql &> /dev/null; then
    echo "[+] Installation de PostgreSQL et des dépendances..."
    apt update && apt install postgresql python3-phonenumbers nginx certbot python3-certbot-nginx wget gpg -y
else
    echo "[i] PostgreSQL et dépendances déjà présents."
fi

# --- ÉTAPE 2 : WKHTMLTOPDF (nécessite libssl1.1, absente d'Ubuntu 24.04) ---
if ! command -v wkhtmltopdf &> /dev/null; then
    echo "[+] Installation de Wkhtmltopdf (version libssl1.1)..."
    cd /tmp
    # libssl1.1 : le numéro de révision change à chaque correctif de sécurité —
    # on détecte la dernière version dans le dépôt, sinon on prend le miroir.
    LIBSSL_DEB=$(wget -qO- http://security.ubuntu.com/ubuntu/pool/main/o/openssl/ \
        | grep -o 'libssl1\.1_1\.1\.1f-1ubuntu2\.[0-9]*_amd64\.deb' | sort -V | tail -1)
    if [ -n "$LIBSSL_DEB" ]; then
        wget -q "http://security.ubuntu.com/ubuntu/pool/main/o/openssl/$LIBSSL_DEB"
    else
        echo "[i] Dépôt Ubuntu inaccessible — utilisation du miroir $MIRROR"
        LIBSSL_DEB="libssl1.1_amd64.deb"
        wget -q -O "$LIBSSL_DEB" "$MIRROR/libssl1.1_amd64.deb"
    fi
    dpkg -i "$LIBSSL_DEB"
    wget -q https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox_0.12.6-1.bionic_amd64.deb \
        || wget -q -O wkhtmltox_0.12.6-1.bionic_amd64.deb "$MIRROR/wkhtmltox_0.12.6-1.bionic_amd64.deb"
    dpkg -i wkhtmltox_0.12.6-1.bionic_amd64.deb
    apt install -f -y
else
    echo "[i] Wkhtmltopdf déjà installé."
fi

# --- ÉTAPE 3 : INSTALLATION ODOO ---
if ! command -v odoo &> /dev/null; then
    echo "[+] Installation d'Odoo 19 (dépôt nightly officiel)..."
    wget -q -O - https://nightly.odoo.com/odoo.key | gpg --dearmor -o /usr/share/keyrings/odoo-archive-keyring.gpg
    echo "deb [signed-by=/usr/share/keyrings/odoo-archive-keyring.gpg] https://nightly.odoo.com/19.0/nightly/deb/ ./" | tee /etc/apt/sources.list.d/odoo.list
    apt update && apt install odoo -y
else
    echo "[i] Odoo est déjà installé sur ce système."
fi

# --- ÉTAPE 4 : NGINX & DOMAINE ---
if [ ! -f /etc/nginx/sites-available/odoo.cfg ]; then
    read -p "Configuration Nginx non trouvée. Entrez votre domaine : " DOMAINE
    if [ ! -z "$DOMAINE" ]; then
        echo "[+] Configuration de Nginx pour $DOMAINE..."
        tee /etc/nginx/sites-available/odoo.cfg <<EOF
upstream odoo { server 127.0.0.1:8069; }
upstream odoochat { server 127.0.0.1:8072; }
server {
    listen 80;
    server_name $DOMAINE www.$DOMAINE ;
    proxy_read_timeout 720s;
    proxy_set_header X-Forwarded-Host \$host;
    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto \$scheme;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header Host \$host;
    # Odoo 17+ : canal temps réel via WebSocket (remplace /longpolling)
    location /websocket {
        proxy_pass http://odoochat;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "Upgrade";
    }
    location / { proxy_pass http://odoo; }
    # Sécurité : ne pas exposer la liste des modules installés
    location = /website/info { deny all; return 404; }
}
EOF
        ln -s /etc/nginx/sites-available/odoo.cfg /etc/nginx/sites-enabled/
        rm -f /etc/nginx/sites-enabled/default
        grep -q "client_max_body_size" /etc/nginx/nginx.conf || sed -i '/http {/a \    client_max_body_size 100M;' /etc/nginx/nginx.conf
        systemctl restart nginx
        certbot --nginx -d $DOMAINE -d www.$DOMAINE --non-interactive --agree-tos -m admin@$DOMAINE
    fi
else
    echo "[i] Configuration Nginx déjà en place."
fi

# --- ÉTAPE 5 : DOSSIERS ET CONFIG ODOO ---
mkdir -p /opt/odoo/custom_addons
chown -R odoo:odoo /opt/odoo/
RESTART_ODOO=0
if ! grep -qE "^addons_path.*custom_addons" /etc/odoo/odoo.conf; then
    echo "[+] Ajout du chemin custom_addons dans odoo.conf..."
    # v2.1 : la ligne du paquet nightly est commentée (";addons_path = ...") — la décommenter
    sed -i -E 's|^;?[[:space:]]*addons_path = .*|addons_path = /usr/lib/python3/dist-packages/odoo/addons,/opt/odoo/custom_addons|' /etc/odoo/odoo.conf
    RESTART_ODOO=1
fi
# proxy_mode : obligatoire derrière Nginx (en-têtes X-Forwarded-*), sinon URLs
# générées et redirections incorrectes.
if ! grep -q "^proxy_mode" /etc/odoo/odoo.conf; then
    echo "[+] Activation de proxy_mode dans odoo.conf..."
    echo "proxy_mode = True" >> /etc/odoo/odoo.conf
    RESTART_ODOO=1
fi
[ "$RESTART_ODOO" = "1" ] && systemctl restart odoo

# --- ÉTAPE 6 : MAJ AUTO (OPTIONNELLE) ---
# ⚠️ AVERTISSEMENT : cette option met à jour Odoo depuis les builds NIGHTLY et
# redémarre le serveur chaque nuit à 04:00, sans intervention humaine.
# Risque : une mise à jour du paquet ne migre pas les schémas des bases
# (équivalent de « -u » non exécuté) — désynchronisation code/base possible.
# À réserver aux instances dont on accepte ce compromis maintenance/risque.
read -p "Activer la MAJ automatique nightly + reboot 04:00 ? [o/N] " MAJAUTO
if [ "$MAJAUTO" = "o" ] || [ "$MAJAUTO" = "O" ]; then
    echo "[+] Configuration du planning de maintenance automatique..."
    apt install unattended-upgrades -y
    tee /etc/apt/apt.conf.d/50unattended-upgrades <<EOF
Unattended-Upgrade::Origins-Pattern {
    "origin=Ubuntu,archive=\${distro_codename}";
    "origin=Ubuntu,archive=\${distro_codename}-security";
    "origin=Ubuntu,archive=\${distro_codename}-updates";
    "site=nightly.odoo.com";
};
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "04:00";
EOF
    echo "APT::Periodic::Unattended-Upgrade \"0\";" > /etc/apt/apt.conf.d/20auto-upgrades
    (crontab -l 2>/dev/null | grep -v "/usr/bin/unattended-upgrade"; echo "0 4 * * * /usr/bin/unattended-upgrade -d") | crontab -
else
    echo "[i] MAJ auto non activée — mises à jour à la main (apt upgrade + logs après)."
fi

echo "--- Analyse et Mise à jour terminées ! ---"
