#!/usr/bin/env bash
#/ Usage: ghe-prune-snapshots
#/ Keep N latest backup snapshots.
set -e

# Bring in the backup configuration
# shellcheck source=share/github-backup-utils/ghe-backup-config
. "$( dirname "${BASH_SOURCE[0]}" )/ghe-backup-config"

# Once we start pruning, this backup will no longer be valid.
# So create or preserve its `incomplete` file and remove the
# `incomplete` file last.
prune_snapshot() {
  local prune_dir
  while read prune_dir; do
    [ -n "$prune_dir" ] || return
    touch "$prune_dir/incomplete"
    find "$prune_dir" -mindepth 1 -maxdepth 1 -not -path "$prune_dir/incomplete" -print0 | xargs -0 rm -rf
    rm -rf "$prune_dir"
  done
}

# First prune all incomplete / failed snapshot directories
prune_dirs="$(ls -1 "$GHE_DATA_DIR"/[0-9]*/incomplete 2>/dev/null || true)"
prune_num=$(echo "$prune_dirs" | grep -v '^$' | wc -l)

if [ $prune_num -gt 0 ]; then
  echo Pruning $prune_num "failed snapshot(s) ..."
  echo "$prune_dirs" | sed 's@/incomplete$@@' | prune_snapshot
fi

# Now prune all expired snapshots. Keep GHE_NUM_SNAPSHOTS around.
snapshot_count=$(ls -1d "$GHE_DATA_DIR"/[0-9]* 2>/dev/null | wc -l)

if [ "$snapshot_count" -gt "$GHE_NUM_SNAPSHOTS" ]; then
  prune_dirs="$(ls -1d "$GHE_DATA_DIR"/[0-9]* | sort -r | awk "NR>$GHE_NUM_SNAPSHOTS")"
  prune_num=$(echo "$prune_dirs" | grep -v '^$' | wc -l)
  echo Pruning $prune_num "expired snapshot(s) ..."
  echo "$prune_dirs" | prune_snapshot
fi
