2019-03-10 17:09:12 +00:00
|
|
|
#!/bin/sh
|
|
|
|
|
2019-03-10 17:30:11 +00:00
|
|
|
echo
|
|
|
|
echo "Taking a new snapshot"
|
|
|
|
|
2019-03-10 17:09:12 +00:00
|
|
|
CONFIG_PATH=/data/options.json
|
|
|
|
NUM_SNAPSHOTS=$(jq --raw-output ".num_snapshots" $CONFIG_PATH)
|
2019-03-10 17:30:11 +00:00
|
|
|
if [ $NUM_SNAPSHOTS -lt 1 ] ; then
|
|
|
|
NUM_SNAPSHOTS=1
|
|
|
|
fi
|
2019-03-10 17:09:12 +00:00
|
|
|
|
2019-03-10 17:30:11 +00:00
|
|
|
# retrieve current snapshot list
|
2019-03-10 17:09:12 +00:00
|
|
|
CURRENT_SNAPSHOTS=$( curl -s -H "X-HASSIO-KEY: $HASSIO_TOKEN" http://hassio/snapshots )
|
2019-03-10 17:30:11 +00:00
|
|
|
STATUS=$(echo "$CURRENT_SNAPSHOTS" | jq --raw-output '.result')
|
|
|
|
if [ ! "$STATUS" = "ok" ] ; then
|
|
|
|
echo "ERROR: Can't retrieve current snapshot list."
|
|
|
|
exit 1
|
|
|
|
fi
|
|
|
|
|
2019-03-10 17:09:12 +00:00
|
|
|
|
|
|
|
# take snapshot (this can take a long time)
|
2019-03-10 17:30:11 +00:00
|
|
|
START_TIMESTAMP=$(date "+%s")
|
2019-03-10 17:09:12 +00:00
|
|
|
RESULT=$( curl -s -H "X-HASSIO-KEY: $HASSIO_TOKEN" --data '{"name":"Automatic Snapshot"}' -X POST http://hassio/snapshots/new/full )
|
|
|
|
SNAPSHOT_TIMESTAMP=$(date "+%s")
|
|
|
|
SNAPSHOT_TIME=$(echo "$SNAPSHOT_TIMESTAMP - $START_TIMESTAMP" | bc)
|
|
|
|
|
2019-03-10 17:30:11 +00:00
|
|
|
# check if snapshot is ok
|
2019-03-10 17:09:12 +00:00
|
|
|
STATUS=$(echo "$RESULT" | jq --raw-output '.result')
|
|
|
|
if [ ! "$STATUS" = "ok" ] ; then
|
|
|
|
echo "Snapshot FAILED after $SNAPSHOT_TIME seconds."
|
|
|
|
exit 1
|
|
|
|
fi
|
|
|
|
|
|
|
|
SLUG=$(echo "$RESULT" | jq --raw-output '.data.slug')
|
|
|
|
echo "Snapshot $SLUG taken SUCCESSFULLY in $SNAPSHOT_TIME seconds."
|
|
|
|
|
2019-03-10 17:30:11 +00:00
|
|
|
# housekeeping:
|
|
|
|
# we take the list of snapshots (which was taken before this snapshot)
|
|
|
|
# we sort by date (reversed), remove the protected snapshots and take
|
|
|
|
# only a list of slugs
|
|
|
|
# then we skip the first NUM_SNAPSHOTS slugs and delete all the rest
|
2019-03-10 17:09:12 +00:00
|
|
|
FIRST_SLUG_TO_DELETE=$(echo "1 + $NUM_SNAPSHOTS" | bc)
|
|
|
|
echo $CURRENT_SNAPSHOTS | jq --raw-output ".data.snapshots | 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 snapshot $SLUG_TO_DELETE"
|
|
|
|
curl -s -H "X-HASSIO-KEY: $HASSIO_TOKEN" -X POST http://hassio/snapshots/$SLUG_TO_DELETE/remove
|
|
|
|
done
|