#!/bin/bash # Configuration BACKUP_SCRIPT="/home/litespeed/mb-backups/backup_all.sh" LOG_DIR="/home/litespeed/mb-backups/logs/auto" ACTION_LOG_FILE="${LOG_DIR}/schedule_actions.log" BACKUP_LOG_PREFIX="${LOG_DIR}/backup_" # Ensure the log directory exists mkdir -p "$LOG_DIR" log_action() { echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" >> "$ACTION_LOG_FILE" } check_and_install_cron() { # Check if cron is installed if ! command -v crontab &> /dev/null; then echo "Cron is not installed. Installing..." sudo dnf install -y cronie fi # Check if cron is running if ! systemctl is-active --quiet crond; then echo "Starting cron service..." sudo systemctl start crond sudo systemctl enable crond fi # Verify cron is running if systemctl is-active --quiet crond; then echo "Cron service is running." else echo "Failed to start cron service." log_action "Failed to start cron service." exit 1 fi } add_update_cron_job() { # Verify Restic password is provided if [ -z "$3" ]; then echo "Restic password is required." log_action "Attempted to add/update a schedule without providing a Restic password." exit 1 fi # Prepare the cron command to include dynamic date in the backup log filename CMD="RESTIC_PASSWORD=\"$3\" $BACKUP_SCRIPT > \"${BACKUP_LOG_PREFIX}\$(date +\\%Y-\\%m-\\%d_\\%H-\\%M-\\%S).log\" 2>&1" # Add or update the cron job (crontab -l | grep -v "$BACKUP_SCRIPT" 2>/dev/null; echo "$2 $CMD") | crontab - local update_msg="Backup schedule updated to: $2" echo "$update_msg" log_action "$update_msg" # Verify if the cron job was added if crontab -l | grep -q "$CMD"; then echo "Cron job added successfully." log_action "Cron job added successfully." else echo "Failed to add cron job." log_action "Failed to add cron job." exit 1 fi } # Main execution check_and_install_cron # Example usage: add or update a cron job # Usage: ./manage_backup_schedule.sh add '0 1 * * *' 'your_restic_password' case $1 in add|update) if [ "$#" -ne 3 ]; then echo "Usage for add/update: $0 {add|update} 'schedule' 'restic_password'" echo "Example: $0 add '0 1 * * *' 'secret_password'" log_action "Incorrect usage for add/update. Correct format not followed." else add_update_cron_job "$@" fi ;; remove) # Functionality to remove cron job can be added here ;; *) echo "Invalid action: $1. Use add, update, or remove." log_action "Invalid action attempted: $1" exit 1 ;; esac