#!/usr/bin/env bash
set -Eeuo pipefail

CONFIG_FILE="${JARVIS_CONFIG:-$HOME/.config/jarvis/jarvis.env}"
if [[ -r "$CONFIG_FILE" ]]; then
    set -a
    # shellcheck disable=SC1090
    . "$CONFIG_FILE"
    set +a
fi

NFS_GROUP="${JARVIS_NFS_GROUP:-nas-backup}"

GATEWAY_WAS_ACTIVE=0
FINISHED=0

cleanup() {
    rc=$?

    if [[ "$GATEWAY_WAS_ACTIVE" -eq 1 ]]; then
        echo
        echo "Redémarrage Hermes gateway..."

        if systemctl --user start hermes-gateway.service; then
            echo "Hermes gateway redémarré."
        else
            echo "ERREUR: impossible de redémarrer Hermes gateway." >&2

            if [[ "$rc" -eq 0 ]]; then
                rc=1
            fi
        fi
    fi

    if [[ "$FINISHED" -eq 0 && "$rc" -ne 0 ]]; then
        echo
        echo "Backup interrompu avec code $rc." >&2
    fi

    exit "$rc"
}

trap cleanup EXIT

echo "=================================================="
echo "  JARVIS SAFE BACKUP"
echo "=================================================="

if systemctl --user is-active \
    --quiet hermes-gateway.service 2>/dev/null
then
    GATEWAY_WAS_ACTIVE=1

    echo "Arrêt temporaire Hermes gateway..."
    systemctl --user stop hermes-gateway.service

    for _ in {1..20}; do
        if ! systemctl --user is-active \
            --quiet hermes-gateway.service 2>/dev/null
        then
            break
        fi

        sleep 0.5
    done

    if systemctl --user is-active \
        --quiet hermes-gateway.service 2>/dev/null
    then
        echo "ERREUR: Hermes gateway ne s'est pas arrêté." >&2
        exit 1
    fi
fi

echo
echo "[1/2] Snapshot Camofox + Open WebUI..."
"$HOME/.local/bin/jarvis-backup-extra"

echo
echo "[2/2] Backup principal avec groupe nas-backup..."
sg "$NFS_GROUP" -c "$HOME/.local/bin/jarvis-backup"

FINISHED=1

echo
echo "JARVIS SAFE BACKUP : OK"
