hassio-addons/auto-backup/backup.sh

48 lines
1.7 KiB
Bash
Raw Normal View History

2021-09-07 21:37:54 +00:00
#!/bin/sh
echo
echo "Taking a new backup"
CONFIG_PATH=/data/options.json
NUM_BACKUPS=$(jq --raw-output ".num_backups" $CONFIG_PATH)
if [ $NUM_BACKUPS -lt 1 ] ; then
NUM_BACKUPS=1
fi
# retrieve current backup list
CURRENT_BACKUPS=$( curl -s -H "X-HASSIO-KEY: $HASSIO_TOKEN" http://hassio/backups )
STATUS=$(echo "$CURRENT_BACKUPS" | jq --raw-output '.result')
if [ ! "$STATUS" = "ok" ] ; then
echo "ERROR: Can't retrieve current backup list."
exit 1
fi
# take backup (this can take a long time)
START_TIMESTAMP=$(date "+%s")
RESULT=$( curl -s -H "X-HASSIO-KEY: $HASSIO_TOKEN" --data '{"name":"Automatic Backup"}' -X POST http://hassio/backups/new/full )
BACKUP_TIMESTAMP=$(date "+%s")
BACKUP_TIME=$(echo "$BACKUP_TIMESTAMP - $START_TIMESTAMP" | bc)
# check if backup is ok
STATUS=$(echo "$RESULT" | jq --raw-output '.result')
if [ ! "$STATUS" = "ok" ] ; then
echo "Backup FAILED after $BACKUP_TIME seconds."
exit 1
fi
SLUG=$(echo "$RESULT" | jq --raw-output '.data.slug')
echo "Backup $SLUG taken SUCCESSFULLY in $BACKUP_TIME seconds."
# housekeeping:
# we take the list of backups (which was taken before this backup)
# we sort by date (reversed), remove the protected backups and take
# only a list of slugs
# then we skip the first NUM_BACKUPS slugs and delete all the rest
FIRST_SLUG_TO_DELETE=$(echo "1 + $NUM_BACKUPS" | bc)
echo $CURRENT_BACKUPS | jq --raw-output ".data.backups | sort_by(.date) | reverse[] | select(.slug != \"$SLUG\") | select (.protected==false) | .slug " | tail -n +$FIRST_SLUG_TO_DELETE | while read SLUG_TO_DELETE
do
echo "Removing backup $SLUG_TO_DELETE"
curl -s -H "X-HASSIO-KEY: $HASSIO_TOKEN" -X POST http://hassio/backups/$SLUG_TO_DELETE/remove
done