#!/bin/sh

set -eu

# outputs 'year <TAB> calendar_week_number <TAB> snapshot_directory' format
old_snapshots() {
  branch="$1"
  older_than_days="$2"
  find "${branch}" -mtime "+${older_than_days}d" \
    -maxdepth 1 -type d -name '????????????????????????????????????????' \
    -exec stat -f '%Sm%N' -t '%Y%t%U%t' {} +
}

cd /home/artifact/snapshot

candidates="$(mktemp)"
trap 'rm -f ${candidates}; trap - EXIT; exit' EXIT INT HUP

for branch in main stable-*; do
  echo "=====CLEANUP ${branch}====="
  echo "Keep WEEKLY snapshots older than 60 days. Remove the rest:"
  old_snapshots "${branch}" 60 | sort -k1,2 -s > "${candidates}"
  sort -k1,2 -su "${candidates}" | comm -13 - "${candidates}" | cut -wf3 | xargs echo rm -r
  echo

  echo "Keep BI-WEEKLY snapshots older than 120 days. Remove the rest:"
  old_snapshots "${branch}" 120 | sort -k1,2 -su | awk '$2%2>0 { print $3 }' | xargs echo rm -r
  echo

  echo "Keep MONTHLY snapshots older than 180 days. Remove the rest:"
  old_snapshots "${branch}" 180 | sort -k1,2 -su | awk '$2%4>0 { print $3 }' | xargs echo rm -r
  echo
  echo "==========================="
done

