#!/usr/bin/env bash
#
# Déploiement Fico (production Ubuntu / Apache)
#
# Usage :
#   ./deploy.sh              # branche main
#   ./deploy.sh develop        # autre branche
#   ./deploy.sh --no-services  # sans redémarrage Apache / worker
#
# Peut être lancé en root (SSH) : les permissions sont corrigées en fin de script.
# Variables optionnelles : FICO_DEPLOY_USER, FICO_WEB_GROUP, FICO_QUEUE_SERVICE
# Voir docs/INSTALLATION-UBUNTU-APACHE.md

set -euo pipefail

BRANCH="main"
RESTART_SERVICES=true
QUEUE_SERVICE="${FICO_QUEUE_SERVICE:-fico-queue}"
DEPLOY_USER="${FICO_DEPLOY_USER:-deploy}"
WEB_GROUP="${FICO_WEB_GROUP:-www-data}"

for arg in "$@"; do
    case "$arg" in
        --no-services)
            RESTART_SERVICES=false
            ;;
        -h|--help)
            sed -n '3,12p' "$0" | sed 's/^# \{0,1\}//'
            exit 0
            ;;
        -*)
            echo "Option inconnue : $arg" >&2
            exit 1
            ;;
        *)
            BRANCH="$arg"
            ;;
    esac
done

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT_DIR"

IS_ROOT=false
if [[ "$(id -u)" -eq 0 ]]; then
    IS_ROOT=true
fi

resolve_owner() {
    if id "$DEPLOY_USER" &>/dev/null; then
        echo "$DEPLOY_USER"
        return
    fi

    if [[ "$IS_ROOT" == true ]]; then
        echo "Avertissement : utilisateur « $DEPLOY_USER » introuvable, propriété root:$WEB_GROUP." >&2
        echo "Créez l'utilisateur ou définissez FICO_DEPLOY_USER." >&2
        echo "root"
        return
    fi

    echo "$(whoami)"
}

fix_permissions() {
    local owner
    owner="$(resolve_owner)"

    echo "==> Correction des permissions ($owner:$WEB_GROUP)"

    chown -R "$owner:$WEB_GROUP" "$ROOT_DIR"

    chown -R "$owner:$WEB_GROUP" storage bootstrap/cache
    chmod -R ug+rwx storage bootstrap/cache
    find storage bootstrap/cache -type d -exec chmod g+s {} +

    if command -v setfacl &>/dev/null; then
        setfacl -R -m "g:${WEB_GROUP}:rwx" storage bootstrap/cache
        setfacl -R -d -m "g:${WEB_GROUP}:rwx" storage bootstrap/cache
    fi
}

run_privileged() {
    if [[ "$IS_ROOT" == true ]]; then
        "$@"
    else
        sudo "$@"
    fi
}

restart_services() {
    if [[ "$RESTART_SERVICES" != true ]]; then
        echo "==> Redémarrage des services ignoré (--no-services)"
        return
    fi

    echo "==> systemctl restart $QUEUE_SERVICE"
    run_privileged systemctl restart "$QUEUE_SERVICE"

    echo "==> systemctl reload apache2"
    run_privileged systemctl reload apache2
}

echo "==> Déploiement Fico ($(pwd))"
echo "    Branche : $BRANCH"
echo "    Utilisateur : $(whoami)"
if [[ "$IS_ROOT" == true ]]; then
    echo "    Mode root : les permissions seront corrigées en fin de script"
fi
echo ""

if [[ "$IS_ROOT" == true ]]; then
    fix_permissions
fi

echo "==> git pull origin $BRANCH"
git pull origin "$BRANCH"

echo "==> composer install --no-dev --optimize-autoloader"
composer install --no-dev --optimize-autoloader

echo "==> npm ci"
npm ci

echo "==> npm run build"
npm run build

echo "==> php artisan migrate --force"
php artisan migrate --force

echo "==> php artisan config:cache"
php artisan config:cache

echo "==> php artisan route:cache"
php artisan route:cache

echo "==> php artisan view:cache"
php artisan view:cache

if [[ "$IS_ROOT" == true ]]; then
    fix_permissions
fi

restart_services

echo ""
echo "Déploiement terminé."
