#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=common.sh
source "$SCRIPT_DIR/common.sh"

DRY_RUN=1
KEEP_RUNS=""
usage() {
  cat <<'USAGE'
Usage: ./scripts/cleanup.sh [--execute] [--keep-runs N]

By default this is a dry-run. It removes old run_* directories beyond KEEP_RUNS
and clears tmp contents.
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --execute)
      DRY_RUN=0
      shift
      ;;
    --keep-runs)
      KEEP_RUNS="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      die "unknown option: $1"
      ;;
  esac
done

load_env
keep="${KEEP_RUNS:-${RETAIN_RUNS:-100}}"
mapfile -t runs < <(find "$HOST_DATA_DIR/runs" -maxdepth 1 -type d -name 'run_*' 2>/dev/null | sort)
delete_count=$(( ${#runs[@]} - keep ))
if (( delete_count > 0 )); then
  for ((i=0; i<delete_count; i++)); do
    if [[ "$DRY_RUN" == "1" ]]; then
      echo "DRY-RUN rm -rf ${runs[$i]}"
    else
      rm -rf "${runs[$i]}"
    fi
  done
fi
if [[ "$DRY_RUN" == "1" ]]; then
  echo "DRY-RUN rm -rf $HOST_DATA_DIR/tmp/*"
else
  find "$HOST_DATA_DIR/tmp" -mindepth 1 -maxdepth 1 -exec rm -rf {} +
fi
df -h "$HOST_DATA_DIR" 2>/dev/null || true
