#!/bin/sh

set -e

# check if its there
if [ ! -x /usr/bin/apt-btrfs-snapshot ]; then
    exit 0
fi

# check if its usable, if list returns a non-zero exit code, 
# we probably run on a system with no snapshot support
if ! /usr/bin/apt-btrfs-snapshot list > /dev/null  2>&1; then
    exit 0
fi

# allow the user to set MaxAge (in days)
#
# By default we automatically prune snapshots using a retain policy:
#       APT::Snapshots::Retain::latest "0";
#       APT::Snapshots::Retain::minutely "0";
#       APT::Snapshots::Retain::hourly "8";
#       APT::Snapshots::Retain::daily "7";
#       APT::Snapshots::Retain::weekly "2";
#       APT::Snapshots::Retain::monthly "0";
#       APT::Snapshots::Retain::yearly "0";
#
# This happens each time a snapshot is created, unless --no-prune is passed,
# but it can also be run manually using `apt-btrfs-snapshot prune`.
#
# Meaning that for each period we keep the configured number of snapshots,
# for example if you have snapshots from
#
#           2024-05-02 12:00
#           2024-05-01 14:00
#           2024-05-01 12:50
#           2024-05-01 12:00
#
# - If our policy is everything 0 with hourly set to 3, we retain 05-02 12:00, and the
#   14:00 and 12:50 snapshots, the latest of each hour
# - If our policy only keeps daily snapshots, we'd keep 2024-05-02 12:00 and
#   2024-05-01 14:00, the latest of each day.
# - If we combine the two:
#    - 2024-05-02 12:00 is kept due to daily and hourly
#    - 2024-05-01 14:00 is kept due to daily and hourly
#    - 2024-05-01 12:50 is kept due to daily and hourly
#   The 2024-05-01 12:00 snapshot is subject to pruning.
#
MaxAge=
eval $(apt-config shell MaxAge APT::Snapshots::MaxAge)

# delete old snapshots
if [ "$MaxAge" ]; then
    apt-btrfs-snapshot delete-older-than "${MaxAge}d"
fi

