#!/bin/bash # Enable strict error handling set -euo pipefail trap 'handle_error $? $LINENO' ERR # 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_" PASSWORD_FILE="/etc/restic-password" LOCK_FILE="/tmp/backup_schedule.lock" SCHEDULE="0 0 * * *" # Default to daily at midnight # Error handling function handle_error() { local exit_code=$1 local line_no=$2 log_action "ERROR: Command failed at line ${line_no} with exit code ${exit_code}" cleanup_and_exit 1 } # Cleanup function cleanup_and_exit() { local exit_code=$1 [ -f "$LOCK_FILE" ] && rm -f "$LOCK_FILE" exit "${exit_code}" } # Ensure single instance ensure_single_instance() { if [ -f "$LOCK_FILE" ]; then if kill -0 "$(cat "$LOCK_FILE")" 2>/dev/null; then log_action "ERROR: Another instance is running" exit 1 fi fi echo $$ > "$LOCK_FILE" } # Logging function log_action() { local timestamp=$(date +'%Y-%m-%d %H:%M:%S') echo "[$timestamp] $1" | tee -a "$ACTION_LOG_FILE" } # Function to configure the cron job configure_cron_job() { if [ ! -f "$PASSWORD_FILE" ]; then log_action "ERROR: Restic password file not found" return 1 fi local restic_password restic_password=$(cat "$PASSWORD_FILE") local cmd="RESTIC_PASSWORD='$restic_password' LOG_FILE='${BACKUP_LOG_PREFIX}\$(date +\%Y-\%m-\%d_\%H-\%M-\%S).log' $BACKUP_SCRIPT > \"\$LOG_FILE\" 2>&1 || echo \"\$(date) Backup failed\" >> \"$ACTION_LOG_FILE\"" # Update the cron job (crontab -l 2>/dev/null | grep -v "$BACKUP_SCRIPT"; echo "$SCHEDULE $cmd") | crontab - log_action "Scheduled daily backup at midnight with command: $cmd" } # Main execution main() { mkdir -p "$LOG_DIR" chmod 750 "$LOG_DIR" ensure_single_instance configure_cron_job cleanup_and_exit 0 } # Execute main function with all arguments main "$@"