#!/bin/bash # Load environment variables from .env file source .env # Function to handle errors handle_error() { echo "Error occurred in script: $1" # Trigger the cleanup process cleanup exit 1 } # Function to clean up (unmount and power off HDD) cleanup() { echo "Cleaning up..." echo "Unmounting HDD..." ./unmount_hdd.sh -f || echo "Failed to unmount HDD" echo "Turning off HDD power..." ./power_off_hdd.sh || echo "Failed to power off HDD" } # Function to retry unmounting retry_umount() { local max_retries=5 local count=0 while [ $count -lt $max_retries ]; do if ./unmount_hdd.sh; then echo "Successfully unmounted HDD." return 0 else echo "Unmount failed. Retrying ($((count + 1))/$max_retries)..." sleep 15 count=$((count + 1)) fi done return 1 } # Set trap to call cleanup on script exit or error trap 'cleanup' EXIT # Check battery level echo "Checking battery level..." ./check_battery.sh || handle_error "check_battery.sh" # Power on HDD echo "Turning on HDD power..." ./power_on_hdd.sh || handle_error "power_on_hdd.sh" # Delay before mounting echo "Waiting before mounting HDD..." sleep 30 # Mount HDD echo "Mounting HDD..." ./mount_hdd.sh || handle_error "mount_hdd.sh" # Run backup echo "Running backup..." ./run_backup.sh || handle_error "run_backup.sh" # Delay before unmounting echo "Waiting before unmounting HDD..." sleep 5 # Unmount HDD echo "Unmounting HDD..." retry_umount || handle_error "unmount_hdd.sh" # Power off HDD echo "Turning off HDD power..." ./power_off_hdd.sh || handle_error "power_off_hdd.sh" echo "Backup process completed successfully."