tmux-stare/prune.sh (view raw)
| 1 | #!/usr/bin/env bash |
| 2 | CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" |
| 3 | source "$CURRENT_DIR/scripts/helpers.sh" |
| 4 | |
| 5 | set -euo pipefail |
| 6 | cd "$(get_opt_dir)" |
| 7 | |
| 8 | DAYS=7 |
| 9 | |
| 10 | CUTOFF=$(date -d "$DAYS days ago" +%Y%m%dT%H%M%S) |
| 11 | |
| 12 | |
| 13 | RED='\033[0;31m' |
| 14 | MAGENTA='\033[0;35m' |
| 15 | YELLOW='\033[0;33m' |
| 16 | RESET='\033[0m' |
| 17 | |
| 18 | # Build set of active session names (those with a _last symlink) |
| 19 | declare -A ACTIVE |
| 20 | for l in *_last; do |
| 21 | [ -L "$l" ] || continue |
| 22 | ACTIVE["${l%_last}"]=1 |
| 23 | done |
| 24 | |
| 25 | DELETED=0 |
| 26 | ORPHANS=0 |
| 27 | FIXED=0 |
| 28 | |
| 29 | for f in *_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9][0-9][0-9]; do |
| 30 | [ -f "$f" ] || continue |
| 31 | name="${f%_*}" |
| 32 | ts="${f##*_}" |
| 33 | |
| 34 | if [[ -v ACTIVE["$name"] ]]; then |
| 35 | # Active session: keep the _last target always, prune old others |
| 36 | target="$(readlink "${name}_last" 2>/dev/null || true)" |
| 37 | # readlink returns an absolute path; compare basenames only |
| 38 | if [ "$f" = "${target##*/}" ]; then continue; fi |
| 39 | if [[ "$ts" < "$CUTOFF" ]]; then |
| 40 | rm "$f" |
| 41 | echo -e "${RED}pruned:${RESET} $f" |
| 42 | DELETED=$((DELETED + 1)) |
| 43 | fi |
| 44 | else |
| 45 | if [[ "$ts" < "$CUTOFF" ]]; then |
| 46 | rm "$f" |
| 47 | echo -e "${MAGENTA}pruned (orphan):${RESET} $f" |
| 48 | DELETED=$((DELETED + 1)) |
| 49 | ORPHANS=$((ORPHANS + 1)) |
| 50 | fi |
| 51 | fi |
| 52 | done |
| 53 | |
| 54 | # Clean dangling _last symlinks (target was deleted) |
| 55 | for l in *_last; do |
| 56 | [ -L "$l" ] || continue |
| 57 | [ -e "$l" ] && continue |
| 58 | rm "$l" |
| 59 | echo -e "${YELLOW}cleaned:${RESET} $l (broken symlink)" |
| 60 | FIXED=$((FIXED + 1)) |
| 61 | done |
| 62 | |
| 63 | # Clean dangling global last symlink |
| 64 | if [ -L "last" ] && [ ! -e "last" ]; then |
| 65 | rm "last" |
| 66 | echo -e "${YELLOW}cleaned:${RESET} last (broken symlink)" |
| 67 | FIXED=$((FIXED + 1)) |
| 68 | fi |
| 69 | |
| 70 | echo "Done. $DELETED session files pruned, $ORPHANS orphan sessions deleted, $FIXED broken symlinks cleaned." |