#!/usr/bin/env bash
set -euo pipefail

mode=${1:---dry-run}
storage_root=${AI_GATEWAY_LEGACY_STORAGE_ROOT:-/var/lib/docker/volumes/easyai-ai-gateway_api_data/_data/static}
maximum_age_seconds=86400

[[ $mode == --dry-run || $mode == --apply ]] || {
  echo 'usage: prune-legacy-generated.sh [--dry-run|--apply]' >&2
  exit 64
}
[[ $storage_root == /var/lib/docker/volumes/*/_data/static && -d $storage_root && ! -L $storage_root ]] || {
  echo 'legacy storage root failed safety validation' >&2
  exit 1
}

candidate_list=$(mktemp)
trap 'rm -f -- "$candidate_list"' EXIT HUP INT TERM
now_epoch=$(date +%s)
while IFS= read -r -d '' file; do
  modified_epoch=$(stat -c '%Y' "$file")
  if (( now_epoch - modified_epoch > maximum_age_seconds )); then
    printf '%s\0' "$file" >>"$candidate_list"
  fi
done < <(find "$storage_root" -xdev -type f -print0)

file_count=$(tr -cd '\0' <"$candidate_list" | wc -c | tr -d ' ')
byte_count=0
while IFS= read -r -d '' file; do
  [[ $file == "$storage_root/"* && ! -L $file ]] || {
    echo "unsafe cleanup candidate: $file" >&2
    exit 1
  }
  byte_count=$((byte_count + $(stat -c '%s' "$file")))
done <"$candidate_list"

if [[ $mode == --apply ]]; then
  while IFS= read -r -d '' file; do
    rm -f -- "$file"
  done <"$candidate_list"
  find "$storage_root" -xdev -depth -type d -empty -delete
fi

printf 'legacy_cleanup=%s files=%s bytes=%s age_seconds_strictly_greater_than=86400\n' \
  "${mode#--}" "$file_count" "$byte_count"
