borg-remote-android/backup-android.sh

84 lines
2.1 KiB
Bash
Raw Permalink Normal View History

2018-09-21 17:27:49 -04:00
#!/data/data/com.termux/files/usr/bin/bash
# Initialize
# if [ -z "$STY" ]; then exec screen -m -S backup-android /bin/bash "$0"; fi
2018-09-21 17:27:49 -04:00
ABSPATH="$(readlink -f "$BASH_SOURCE")"
2018-11-26 19:31:35 -05:00
set -x
2018-09-21 17:27:49 -04:00
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}'
2018-09-21 17:27:49 -04:00
}
# 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
2018-09-21 17:27:49 -04:00
}
2019-09-15 10:55:36 -04:00
function prune() {
if [ -z "$PRUNE_COMMAND" ]; then
echo "Not pruning" >&2
return
fi
run_remote "${PRUNE_COMMAND[@]}" "$BORG_REPO"
2019-09-15 10:55:36 -04:00
}
2018-09-21 17:27:49 -04:00
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
2018-09-23 13:58:41 -04:00
if (( RETRIES == 0 )); then
# We exceeded the retry limit. Fail
return 1
fi
2018-09-21 17:27:49 -04:00
# Next, instruct the host to create a borg
echo "Running borg..."
run_remote "${CREATE_COMMAND[@]}" "$BORG_REPO::$HOSTNAME-$(uuidgen)" . || return 2
2018-09-21 17:27:49 -04:00
}
# 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" )"
2019-09-15 10:55:36 -04:00
# Prune
prune
2018-09-21 17:27:49 -04:00
echo "Completed $(date +%F-%T)"
echo "Duration: $DURATION"
if (( RESULT == 0 )); then
termux-notification --title "Backup completed successfully in $DURATION"
2018-09-21 17:27:49 -04:00
else
termux-notification --title "Backup failed in $DURATION"
2018-09-21 17:27:49 -04:00
fi
# Remove our wakelock
termux-wake-unlock
printf "^c to exit"
cat