Last active 1 week ago

dnf-auto-update.sh Raw
1#!/usr/bin/env bash
2set -euo pipefail
3
4# --- Réglages ---
5LOGFILE="/var/log/auto-upgrade.log"
6LOCKFILE="/var/run/auto-upgrade.lock"
7
8# --- Vérification root ---
9if [ "$(id -u)" -ne 0 ]; then
10 echo "Ce script doit être exécuté en root." >&2
11 exit 1
12fi
13
14# --- Logging ---
15umask 022
16mkdir -p "$(dirname "$LOGFILE")"
17if [ -t 1 ]; then
18 exec > >(tee -a "$LOGFILE") 2>&1
19else
20 exec >>"$LOGFILE" 2>&1
21fi
22
23echo "===== $(date -Is) : démarrage auto-upgrade (AlmaLinux) ====="
24
25# --- Lock pour éviter les collisions ---
26exec 9>"$LOCKFILE"
27if ! flock -n 9; then
28 echo "Un autre auto-upgrade est déjà en cours, arrêt."
29 exit 0
30fi
31
32# --- Fonction de détection reboot ---
33reboot_required() {
34 if command -v needs-restarting >/dev/null 2>&1; then
35 if needs-restarting -r >/dev/null 2>&1; then
36 return 1 # pas de reboot
37 else
38 return 0 # reboot requis
39 fi
40 fi
41
42 local running latest
43 running="$(uname -r)"
44 latest="$(rpm -q kernel-core --qf '%{VERSION}-%{RELEASE}.%{ARCH}\n' 2>/dev/null | sort -V | tail -n1)"
45 [ -z "$latest" ] && latest="$(rpm -q kernel --qf '%{VERSION}-%{RELEASE}.%{ARCH}\n' 2>/dev/null | sort -V | tail -n1)"
46 if [ -n "$latest" ] && [ "$latest" != "$running" ]; then
47 return 0
48 fi
49 return 1
50}
51
52# --- Étapes de mise à jour ---
53echo "[1/4] dnf makecache --refresh"
54dnf -y makecache --refresh
55
56echo "[2/4] dnf upgrade --refresh"
57dnf -y upgrade --refresh
58
59echo "[3/4] dnf distro-sync"
60dnf -y distro-sync
61
62echo "[4/4] dnf autoremove"
63dnf -y autoremove || true
64
65# --- Reboot si nécessaire ---
66if reboot_required; then
67 echo "Reboot nécessaire (kernel ou libs critiques)."
68 /sbin/reboot
69else
70 echo "Pas besoin de reboot."
71fi
72
73echo "===== $(date -Is) : fin auto-upgrade ====="
74echo "--------------------------------------------------------"
75exit 0