system-scripts/backup/backup2cloud.sh

94 lines
2.4 KiB
Bash
Executable File

#!/bin/bash
# ensure prerequisites are installed: rclone p7zip-full
# run `rclone config` to set up your target, put the name you choose as REMOTE_NAME
# edit .env and add an ENC_PASSWORD used for encryption, can also put variable overrides there
# the directory name will be used as archive name by default
# usage: script.sh [path] [archive name override]
# Default values
SOURCE_DIR="$1"
CURRENT_DATE_TIME=$(date +"%Y%m%d_%H%M%S_%s")
REMOTE_NAME="onedrive"
REMOTE_DIR="Backups/"
# Load environment variables from .env file
source .env
# Check if TEMP_DIR is set
if [ -z "$TEMP_DIR" ]; then
echo "Error: TEMP_DIR environment variable is not set."
exit 1
else
echo "Temporary directory: $TEMP_DIR"
sleep 1
fi
DESTINATION_DIR=$(mktemp -d --tmpdir=$TEMP_DIR)
# Check if ENC_PASSWORD is set
if [ -z "$ENC_PASSWORD" ]; then
echo "Error: ENC_PASSWORD environment variable is not set."
exit 1
fi
# Check if source directory is provided as an argument
if [ "$#" -eq 0 ]; then
echo "Error: Please provide the source directory as an argument."
exit 1
fi
# Check if source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
echo "Error: Source directory '$SOURCE_DIR' does not exist."
exit 1
fi
if [ "$SOURCE_DIR" == "." ]; then
SOURCE_DIR=$(pwd)
fi
SOURCE_DIR_NAME=$(basename "$SOURCE_DIR")
ARCHIVE_NAME="${SOURCE_DIR_NAME}"
# Use the provided archive name if the second parameter is present
if [ "$#" -eq 2 ]; then
ARCHIVE_NAME="$2"
fi
ARCHIVE_NAME="$(hostname)_${ARCHIVE_NAME}_${CURRENT_DATE_TIME}"
ARCHIVE_FILE="$DESTINATION_DIR/${ARCHIVE_NAME}.7z"
# Function to clean up temporary files on exit
cleanup() {
echo "Cleaning up at: $DESTINATION_DIR"
rm -rf "$DESTINATION_DIR"
}
echo "Temporary directory: $DESTINATION_DIR"
trap cleanup EXIT
# Archive, compress, and encrypt the directory
7z a -t7z -m0=lzma2 -mx=9 -mhe=on -p"$ENC_PASSWORD" "$ARCHIVE_FILE" "$SOURCE_DIR"
if [ $? -eq 0 ]; then
echo "Archiving successful. Beginning upload."
else
echo "Error ($?): Archiving failed. Check path permissions."
exit 1
fi
# Upload to OneDrive using rclone
rclone copy "$ARCHIVE_FILE" "$REMOTE_NAME:$REMOTE_DIR" -P
# Check if the upload was successful
if [ $? -eq 0 ]; then
echo "Upload successful. Cleaning up temporary files."
cleanup
else
echo "Error: Upload failed. Check your internet connection or OneDrive configuration."
exit 1
fi