mb-backup-manager/scripts/imports/manage_backup_schedule.sh

92 lines
2.7 KiB
Bash
Raw Normal View History

2024-09-18 16:53:20 +00:00
#!/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_"
2024-11-12 18:15:11 +00:00
2024-11-12 19:18:30 +00:00
# Ensure the log directory exists
mkdir -p "$LOG_DIR"
2024-09-18 16:53:20 +00:00
log_action() {
2024-11-12 19:18:30 +00:00
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" >> "$ACTION_LOG_FILE"
2024-09-18 16:53:20 +00:00
}
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
}
2024-11-12 19:18:30 +00:00
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
2024-11-12 18:29:16 +00:00
fi
2024-09-18 16:53:20 +00:00
2024-11-12 19:18:30 +00:00
# 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"
2024-09-18 16:53:20 +00:00
2024-11-12 19:18:30 +00:00
# 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"
2024-11-12 18:15:11 +00:00
# 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
2024-11-12 18:15:11 +00:00
}
# 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'
2024-11-12 19:18:30 +00:00
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
2024-11-12 19:18:30 +00:00
;;
*)
echo "Invalid action: $1. Use add, update, or remove."
log_action "Invalid action attempted: $1"
exit 1
;;
esac