From 456262ca655e08e49582f6c07df2ea11fb48b9a6 Mon Sep 17 00:00:00 2001 From: "tiago.aica" Date: Sun, 15 Feb 2026 17:42:42 +0000 Subject: [PATCH] improve log system --- debian/gui_manager.sh | 135 +++++++++++++++++++++++++++----------- debian/set_mac_wifi.sh | 32 ++++++++- debian/set_static_ip.sh | 35 ++++++++-- debian/setup_raspberry.sh | 33 +++++++++- debian/upgrade_debian.sh | 33 +++++++++- 5 files changed, 216 insertions(+), 52 deletions(-) diff --git a/debian/gui_manager.sh b/debian/gui_manager.sh index 0a0ea53..a779e2f 100644 --- a/debian/gui_manager.sh +++ b/debian/gui_manager.sh @@ -1,5 +1,4 @@ #!/bin/bash - # ============================================= # Graphical Environment Manager Script # Disables/enables graphical environment to save RAM @@ -12,9 +11,37 @@ # --- Configuration --- LOG_FILE="/var/log/gui_manager.log" +MAX_LOG_SIZE_KB=1024 # 1MB # --- Functions --- +# Função de Log (modificada para usar logger) +log() { + local message="$1" + local timestamp=$(date '+%Y-%m-%d %H:%M:%S') + # Escreve no ficheiro de log + echo "$timestamp: $message" | tee -a "$LOG_FILE" + # Envia para o syslog (opcional) + logger -t "gui_manager" "$message" +} + +# Função para limitar o tamanho do log +limit_log_size() { + local log_file="$1" + local max_size_kb="$2" + local max_size_bytes=$((max_size_kb * 1024)) + + if [ -f "$log_file" ]; then + local current_size=$(stat -c %s "$log_file" 2>/dev/null || wc -c < "$log_file" 2>/dev/null) + + if [ "$current_size" -gt "$max_size_bytes" ]; then + log "Aviso: Ficheiro de log $log_file excedeu $max_size_kb KB. A truncar..." + tail -n 500 "$log_file" > "${log_file}.tmp" && mv "${log_file}.tmp" "$log_file" + log "Ficheiro de log truncado. As últimas 500 linhas foram mantidas." + fi + fi +} + # Function to check if system uses systemd is_systemd() { [ -d /run/systemd/system ] && return 0 || return 1 @@ -42,128 +69,155 @@ get_current_target() { if is_systemd; then systemctl get-default else - echo "System doesn't use systemd" + log "System doesn't use systemd" + return 1 fi } # Function to show GUI status show_gui_status() { if ! is_systemd; then - echo "$(date): System doesn't use systemd" | tee -a "$LOG_FILE" + log "System doesn't use systemd" return 1 fi current_target=$(get_current_target) dm=$(get_display_manager) - echo "$(date): Current system target: $current_target" | tee -a "$LOG_FILE" - echo "$(date): Display Manager: $(basename "$dm")" | tee -a "$LOG_FILE" + log "Current system target: $current_target" + log "Display Manager: $(basename "$dm")" if [ "$current_target" = "graphical.target" ]; then - echo "$(date): Graphical environment is ENABLED" | tee -a "$LOG_FILE" + log "Graphical environment is ENABLED" else - echo "$(date): Graphical environment is DISABLED" | tee -a "$LOG_FILE" + log "Graphical environment is DISABLED" fi # Show memory usage - echo "$(date): Memory usage:" | tee -a "$LOG_FILE" - free -h | awk '/^Mem:/ {print " Total: " $2 ", Used: " $3 ", Free: " $4}' | tee -a "$LOG_FILE" + log "Memory usage:" + free -h | awk '/^Mem:/ {log " Total: " $2 ", Used: " $3 ", Free: " $4}' } # Function to disable graphical environment disable_gui() { if ! is_systemd; then - echo "$(date): Error: This system doesn't use systemd" | tee -a "$LOG_FILE" + log "Error: This system doesn't use systemd" return 1 fi current_target=$(get_current_target) if [ "$current_target" != "graphical.target" ]; then - echo "$(date): Graphical environment is already disabled" | tee -a "$LOG_FILE" + log "Graphical environment is already disabled" return 0 fi - echo "$(date): Disabling graphical environment..." | tee -a "$LOG_FILE" + log "Disabling graphical environment..." # Get current display manager dm=$(get_display_manager) if [ "$dm" = "unknown" ]; then - echo "$(date): Error: Could not determine display manager" | tee -a "$LOG_FILE" + log "Error: Could not determine display manager" return 1 fi # Show memory usage before - echo "$(date): Memory usage before disabling GUI:" | tee -a "$LOG_FILE" - free -h | awk '/^Mem:/ {print " Total: " $2 ", Used: " $3 ", Free: " $4}' | tee -a "$LOG_FILE" + log "Memory usage before disabling GUI:" + free -h | awk '/^Mem:/ {log " Total: " $2 ", Used: " $3 ", Free: " $4}' # Stop display manager - echo "$(date): Stopping display manager $(basename "$dm")..." | tee -a "$LOG_FILE" - systemctl stop "$(basename "$dm")" + log "Stopping display manager $(basename "$dm")..." + if ! systemctl stop "$(basename "$dm")"; then + log "Error: Failed to stop display manager $(basename "$dm")" + return 1 + fi # Disable graphical target - echo "$(date): Setting default target to multi-user.target..." | tee -a "$LOG_FILE" - systemctl set-default multi-user.target + log "Setting default target to multi-user.target..." + if ! systemctl set-default multi-user.target; then + log "Error: Failed to set default target to multi-user.target" + return 1 + fi # Show memory usage after - echo "$(date): Memory usage after disabling GUI:" | tee -a "$LOG_FILE" - free -h | awk '/^Mem:/ {print " Total: " $2 ", Used: " $3 ", Free: " $4}' | tee -a "$LOG_FILE" + log "Memory usage after disabling GUI:" + free -h | awk '/^Mem:/ {log " Total: " $2 ", Used: " $3 ", Free: " $4}' - echo "$(date): Graphical environment disabled successfully" | tee -a "$LOG_FILE" + log "Graphical environment disabled successfully" return 0 } # Function to enable graphical environment enable_gui() { if ! is_systemd; then - echo "$(date): Error: This system doesn't use systemd" | tee -a "$LOG_FILE" + log "Error: This system doesn't use systemd" return 1 fi current_target=$(get_current_target) if [ "$current_target" = "graphical.target" ]; then - echo "$(date): Graphical environment is already enabled" | tee -a "$LOG_FILE" + log "Graphical environment is already enabled" return 0 fi - echo "$(date): Enabling graphical environment..." | tee -a "$LOG_FILE" + log "Enabling graphical environment..." # Get current display manager dm=$(get_display_manager) if [ "$dm" = "unknown" ]; then - echo "$(date): Error: Could not determine display manager" | tee -a "$LOG_FILE" + log "Error: Could not determine display manager" return 1 fi # Enable graphical target - echo "$(date): Setting default target to graphical.target..." | tee -a "$LOG_FILE" - systemctl set-default graphical.target + log "Setting default target to graphical.target..." + if ! systemctl set-default graphical.target; then + log "Error: Failed to set default target to graphical.target" + return 1 + fi # Start display manager - echo "$(date): Starting display manager $(basename "$dm")..." | tee -a "$LOG_FILE" - systemctl start "$(basename "$dm")" + log "Starting display manager $(basename "$dm")..." + if ! systemctl start "$(basename "$dm")"; then + log "Error: Failed to start display manager $(basename "$dm")" + return 1 + fi - echo "$(date): Graphical environment enabled successfully" | tee -a "$LOG_FILE" + log "Graphical environment enabled successfully" return 0 } +# Function to format free output for logging +format_free_output() { + free -h | awk '/^Mem:/ { + log " Total: " $2 ", Used: " $3 ", Free: " $4 + }' +} + # --- Main Execution --- +# Check if running as root +if [ "$(id -u)" -ne 0 ]; then + echo "This script must be run as root" >&2 + exit 1 +fi + # Create log directory if it doesn't exist -mkdir -p /var/log +mkdir -p "$(dirname "$LOG_FILE")" +limit_log_size "$LOG_FILE" "$MAX_LOG_SIZE_KB" # Verifica o tamanho do log no início + +# Log script execution start +log "Starting GUI Manager Script with action: ${1:-status}" # Determine action based on parameters or environment variable ACTION="" - # Check for command line parameter if [ $# -gt 0 ]; then ACTION="$1" fi - # Check for environment variable if no parameter provided if [ -z "$ACTION" ] && [ -n "$GUI_ACTION" ]; then ACTION="$GUI_ACTION" fi - # Default to status if no action specified if [ -z "$ACTION" ]; then ACTION="status" @@ -173,17 +227,20 @@ fi case "$ACTION" in disable) disable_gui + exit $? ;; enable) enable_gui + exit $? ;; status) show_gui_status + exit $? ;; *) - echo "Usage: $0 [enable|disable|status]" - echo "Or: GUI_ACTION=enable|disable $0" - echo "Invalid action: $ACTION" + log "Usage: $0 [enable|disable|status]" + log "Or: GUI_ACTION=enable|disable $0" + log "Invalid action: $ACTION" exit 1 ;; -esac +esac \ No newline at end of file diff --git a/debian/set_mac_wifi.sh b/debian/set_mac_wifi.sh index 04cea3d..b888977 100644 --- a/debian/set_mac_wifi.sh +++ b/debian/set_mac_wifi.sh @@ -8,13 +8,37 @@ LOG_FILE="/var/log/network_config.log" UDEV_RULES_FILE="/etc/udev/rules.d/81-mac-spoof.rules" IFACE="eth0" WLAN_IFACE="wlan0" +MAX_LOG_SIZE_KB=1024 # 1MB # --- Funções Auxiliares --- -# Função de Log +# Função de Log (modificada para usar logger) log() { + local message="$1" local timestamp=$(date '+%Y-%m-%d %H:%M:%S') - echo "$timestamp: $1" | tee -a "$LOG_FILE" + + # Escreve no ficheiro de log + echo "$timestamp: $message" | tee -a "$LOG_FILE" + + # Envia para o syslog (opcional) + logger -t "network_config" "$message" +} + +# Função para limitar o tamanho do log +limit_log_size() { + local log_file="$1" + local max_size_kb="$2" + local max_size_bytes=$((max_size_kb * 1024)) + + if [ -f "$log_file" ]; then + local current_size=$(stat -c %s "$log_file" 2>/dev/null || wc -c < "$log_file" 2>/dev/null) + + if [ "$current_size" -gt "$max_size_bytes" ]; then + log "Aviso: Ficheiro de log $log_file excedeu $max_size_kb KB. A truncar..." + tail -n 500 "$log_file" > "${log_file}.tmp" && mv "${log_file}.tmp" "$log_file" + log "Ficheiro de log truncado. As últimas 500 linhas foram mantidas." + fi + fi } # Função para verificar se a interface tem IP @@ -273,8 +297,9 @@ monitor_network_task() { if force_ip_renewal "$IFACE"; then log "Monitor: Renovação de IP bem-sucedida. Wi-Fi permanece ativo até confirmação." else - log "Monitor: Falha ao renovar IP. Ativando Wi-Fi como fallback..." + log "Monitor: Falha ao renovar IP." if ip link show "$WLAN_IFACE" &> /dev/null && ip link show "$WLAN_IFACE" | grep -q "DOWN"; then + log "Ativando Wi-Fi como fallback..." if ip link set "$WLAN_IFACE" up; then log "Monitor: Wi-Fi ($WLAN_IFACE) ativado como fallback." else @@ -331,6 +356,7 @@ if [ "$(id -u)" -ne 0 ]; then fi mkdir -p "$(dirname "$LOG_FILE")" +limit_log_size "$LOG_FILE" "$MAX_LOG_SIZE_KB" # Verifica o tamanho do log no início # 1. Verificar se a interface existe if ! ip link show "$IFACE" &> /dev/null; then diff --git a/debian/set_static_ip.sh b/debian/set_static_ip.sh index d5d916e..f38af78 100644 --- a/debian/set_static_ip.sh +++ b/debian/set_static_ip.sh @@ -14,12 +14,37 @@ DEFAULT_GATEWAY="${GATEWAY_ENV:-10.10.0.1}" # Use GATEWAY_ENV if provided, othe DNS_SERVERS="8.8.8.8 8.8.4.4" LOG_FILE="/var/log/set_static_ip.log" NETPLAN_DIR="/etc/netplan" +MAX_LOG_SIZE_KB=1024 # 1MB -# --- Functions --- +# --- Funções Auxiliares --- -# Function to log messages +# Função de Log (modificada para usar logger) log() { - echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE" + local message="$1" + local timestamp=$(date '+%Y-%m-%d %H:%M:%S') + + # Escreve no ficheiro de log + echo "$timestamp: $message" | tee -a "$LOG_FILE" + + # Envia para o syslog (opcional) + logger -t "set_static_ip" "$message" +} + +# Função para limitar o tamanho do log +limit_log_size() { + local log_file="$1" + local max_size_kb="$2" + local max_size_bytes=$((max_size_kb * 1024)) + + if [ -f "$log_file" ]; then + local current_size=$(stat -c %s "$log_file" 2>/dev/null || wc -c < "$log_file" 2>/dev/null) + + if [ "$current_size" -gt "$max_size_bytes" ]; then + log "Aviso: Ficheiro de log $log_file excedeu $max_size_kb KB. A truncar..." + tail -n 500 "$log_file" > "${log_file}.tmp" && mv "${log_file}.tmp" "$log_file" + log "Ficheiro de log truncado. As últimas 500 linhas foram mantidas." + fi + fi } # Function to fix netplan permissions @@ -231,8 +256,8 @@ configure_static_ip() { local interface local dns="$DNS_SERVERS" - # Create log directory if it doesn't exist - mkdir -p /var/log + mkdir -p "$(dirname "$LOG_FILE")" + limit_log_size "$LOG_FILE" "$MAX_LOG_SIZE_KB" # Verifica o tamanho do log no início # Get active interface if ! interface=$(get_active_interface); then diff --git a/debian/setup_raspberry.sh b/debian/setup_raspberry.sh index 0a865e3..cfee1f6 100644 --- a/debian/setup_raspberry.sh +++ b/debian/setup_raspberry.sh @@ -9,6 +9,7 @@ GITHUB_REPO="https://gitea.spiralragetech.com/tiago.aica/scripts/raw/branch/main/debian" SCRIPT_DIR="/usr/local/bin" LOG_FILE="/var/log/raspberry_setup.log" +MAX_LOG_SIZE_KB=1024 # 1MB # Colors for output RED='\033[0;31m' @@ -17,9 +18,33 @@ YELLOW='\033[1;33m' BLUE='\033[1;34m' NC='\033[0m' # No Color -# Function to log messages +# Função de Log (modificada para usar logger) log() { - echo -e "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE" + local message="$1" + local timestamp=$(date '+%Y-%m-%d %H:%M:%S') + + # Escreve no ficheiro de log + echo "$timestamp: $message" | tee -a "$LOG_FILE" + + # Envia para o syslog (opcional) + logger -t "raspberry_setup" "$message" +} + +# Função para limitar o tamanho do log +limit_log_size() { + local log_file="$1" + local max_size_kb="$2" + local max_size_bytes=$((max_size_kb * 1024)) + + if [ -f "$log_file" ]; then + local current_size=$(stat -c %s "$log_file" 2>/dev/null || wc -c < "$log_file" 2>/dev/null) + + if [ "$current_size" -gt "$max_size_bytes" ]; then + log "Aviso: Ficheiro de log $log_file excedeu $max_size_kb KB. A truncar..." + tail -n 500 "$log_file" > "${log_file}.tmp" && mv "${log_file}.tmp" "$log_file" + log "Ficheiro de log truncado. As últimas 500 linhas foram mantidas." + fi + fi } # Function to ask for confirmation @@ -482,7 +507,9 @@ main() { log "Starting Raspberry Pi setup..." # Create script directory if it doesn't exist - mkdir -p "$SCRIPT_DIR" + mkdir -p "$(dirname "$LOG_FILE")" + limit_log_size "$LOG_FILE" "$MAX_LOG_SIZE_KB" # Verifica o tamanho do log no início + # Install dependencies install_dependencies diff --git a/debian/upgrade_debian.sh b/debian/upgrade_debian.sh index 347c22b..2ee4d47 100644 --- a/debian/upgrade_debian.sh +++ b/debian/upgrade_debian.sh @@ -13,10 +13,35 @@ GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[1;34m' NC='\033[0m' # No Color +MAX_LOG_SIZE_KB=1024 # 1MB -# Function to log messages +# Função de Log (modificada para usar logger) log() { - echo -e "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE" + local message="$1" + local timestamp=$(date '+%Y-%m-%d %H:%M:%S') + + # Escreve no ficheiro de log + echo "$timestamp: $message" | tee -a "$LOG_FILE" + + # Envia para o syslog (opcional) + logger -t "debian_upgrade" "$message" +} + +# Função para limitar o tamanho do log +limit_log_size() { + local log_file="$1" + local max_size_kb="$2" + local max_size_bytes=$((max_size_kb * 1024)) + + if [ -f "$log_file" ]; then + local current_size=$(stat -c %s "$log_file" 2>/dev/null || wc -c < "$log_file" 2>/dev/null) + + if [ "$current_size" -gt "$max_size_bytes" ]; then + log "Aviso: Ficheiro de log $log_file excedeu $max_size_kb KB. A truncar..." + tail -n 500 "$log_file" > "${log_file}.tmp" && mv "${log_file}.tmp" "$log_file" + log "Ficheiro de log truncado. As últimas 500 linhas foram mantidas." + fi + fi } # Function to ask for confirmation @@ -190,6 +215,10 @@ main() { exit 1 fi + mkdir -p "$(dirname "$LOG_FILE")" + limit_log_size "$LOG_FILE" "$MAX_LOG_SIZE_KB" # Verifica o tamanho do log no início + + # Check if this is a Debian system if [ ! -f /etc/debian_version ]; then log "${RED}This script is only for Debian-based systems.${NC}"