#!/bin/sh -euf

# Keep only the last 2 backups from boot-hooks/new-release.d/000-backup.
# This avoids cluttering up userdata over time, especially for those that
# switches channel frequently, and also since some earlier backups include some
# unnecessary data and is bigger than needed.
#
# Credit goes to https://stackoverflow.com/a/34862475, except each argument is
# expanded to its long form for self-documenting purpose (GNU-specific,
# probably).

cd /userdata/backups || exit 0 # No dir, no backup to clean.
# See the SO answer for known caveat of this pipeline.
# shellcheck disable=SC2010
ls --sort=time --indicator-style=slash \
    | grep --invert-match '/$' \
    | tail --lines=+3 \
    | xargs --delimiter='\n' --no-run-if-empty rm --
