#!/data/data/com.termux/files/usr/bin/bash # Initialize # if [ -z "$STY" ]; then exec screen -m -S backup-android /bin/bash "$0"; fi ABSPATH="$(readlink -f "$BASH_SOURCE")" set -x cd "${ABSPATH%/*}" || { echo "Cannot change directory" >&2; exit 1; } test -f ./env && source ./env || { echo "Unable to source user variables in $PWD"; exit 1; } # From https://serverfault.com/a/799198 # Since Termux has no uuidgen command, we need to create one randomly function uuidgen() { od -x /dev/urandom | head -1 | awk '{OFS="-"; print $2$3,$4,$5,$6,$7$8$9}' } # From https://unix.stackexchange.com/a/27014 function time_diff { # Find the time difference between the two arguments (in seconds) local T="$(( "$1" - "$2" ))" local D=$((T/60/60/24)) local H=$((T/60/60%24)) local M=$((T/60%60)) local S=$((T%60)) (( $D > 0 )) && printf '%dd ' $D (( $H > 0 )) && printf '%dh ' $H (( $M > 0 )) && printf '%dm ' $M (( $D > 0 || $H > 0 || $M > 0 )) && printf 'and ' printf '%ds\n' $S } function prune() { if [ -z "$PRUNE_COMMAND" ]; then echo "Not pruning" >&2 return fi run_remote "${PRUNE_COMMAND[@]}" "$BORG_REPO" } function backup() { # First, we need to rsync our changes to the host echo "Running rsync..." local RETRIES=10 while (( RETRIES > 0 )); do # Try to rsync "${RSYNC_COMMAND[@]}" "$SOURCE_LOCATION" "$REMOTE_HOST:$DESTINATION_LOCATION" && break (( RETRIES-- )) echo "rsync failed. Retrying $RETRIES more times. Sleeping 10s" sleep 10s done if (( RETRIES == 0 )); then # We exceeded the retry limit. Fail return 1 fi # Next, instruct the host to create a borg echo "Running borg..." run_remote "${CREATE_COMMAND[@]}" "$BORG_REPO::$HOSTNAME-$(uuidgen)" . || return 2 } # Take wakelock so we don't fall asleep termux-wake-lock START_TIME="$(date +%s)" # Perform the backup backup RESULT=$? DURATION="$(time_diff "$(date +%s)" "$START_TIME" )" # Prune prune echo "Completed $(date +%F-%T)" echo "Duration: $DURATION" if (( RESULT == 0 )); then termux-notification --title "Backup completed successfully in $DURATION" else termux-notification --title "Backup failed in $DURATION" fi # Remove our wakelock termux-wake-unlock printf "^c to exit" cat