#!/bin/bash SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" . "${SCRIPT_DIR}/logging.sh" SCRIPTS=( "check-disk-usage.sh" "check-power-usage.sh" "check-temperature.sh" ) CheckScriptExists() { local script="$1" local script_path="${SCRIPT_DIR}/${script}" if [[ -f "$script_path" && -x "$script_path" ]]; then return 0 elif [[ -f "$script_path" ]]; then LogWarning "Script $script exists but is not executable. Making it executable..." chmod +x "$script_path" return 0 else return 1 fi } ManageCrontabEntry() { local script="$1" local script_path="${SCRIPT_DIR}/${script}" local cron_pattern="* * * * * ${script_path}" local current_crontab current_crontab=$(crontab -l 2>/dev/null || echo "") if echo "$current_crontab" | grep -q "$script_path"; then LogInformation "Crontab entry for $script already exists" if echo "$current_crontab" | grep -q "^\* \* \* \* \* ${script_path}"; then LogInformation "Entry for $script is already set to run every minute" else LogInformation "Updating $script to run every minute" local new_crontab new_crontab=$(echo "$current_crontab" | grep -v "$script_path") new_crontab="${new_crontab}${new_crontab:+$'\n'}${cron_pattern}" echo "$new_crontab" | crontab - LogInformation "Updated crontab entry for $script" fi else LogInformation "Adding new crontab entry for $script" local new_crontab="${current_crontab}${current_crontab:+$'\n'}${cron_pattern}" echo "$new_crontab" | crontab - LogInformation "Added crontab entry for $script" fi } BackupCrontab() { local backup_file="${SCRIPT_DIR}/crontab_backup_$(date +%Y%m%d_%H%M%S)" crontab -l > "$backup_file" 2>/dev/null if [[ $? -eq 0 ]]; then LogInformation "Crontab backed up to: $backup_file" else LogWarning "No existing crontab to backup or backup failed" fi } Main() { LogInformation "Starting crontab setup for server management scripts" BackupCrontab for script in "${SCRIPTS[@]}"; do LogInformation "Processing $script..." if CheckScriptExists "$script"; then LogInformation "Script $script found and is executable" ManageCrontabEntry "$script" else LogWarning "Script $script not found or not accessible, skipping..." fi done LogInformation "Crontab setup completed" LogInformation "Current crontab entries:" crontab -l 2>/dev/null | grep -E "(check-disk-usage|check-power-usage|check-temperature)" || LogInformation "No matching entries found" } Main "$@"