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

DIR="/home/ubuntu/msc-navigator/site/shots"
LOG="/home/ubuntu/logs/cleanup-msc-shots.log"
TTL_MINUTES=$((15 * 24 * 60))

mkdir -p "$(dirname "$LOG")"

{
  echo "[$(date -Is)] cleanup start dir=$DIR ttl_minutes=$TTL_MINUTES"
  if [[ ! -d "$DIR" ]]; then
    echo "[$(date -Is)] dir missing, nothing to do"
    exit 0
  fi

  before_count=$(find "$DIR" -type f \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' \) | wc -l)
  before_size=$(du -sh "$DIR" 2>/dev/null | awk '{print $1}')

  # Delete image files older than 96h. Print deleted files to log.
  find "$DIR" -type f \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' \) -mmin +"$TTL_MINUTES" -print -delete

  # Remove empty subdirectories, but never the root dir itself.
  find "$DIR" -mindepth 1 -type d -empty -delete

  after_count=$(find "$DIR" -type f \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' \) | wc -l)
  after_size=$(du -sh "$DIR" 2>/dev/null | awk '{print $1}')
  echo "[$(date -Is)] cleanup done files_before=$before_count size_before=$before_size files_after=$after_count size_after=$after_size"
} >> "$LOG" 2>&1
