#!/bin/sh
# [2026-11-03] The user: "keep files, logs for just one week" (everything older is on the desktop copy, synced nightly 19:00 ET).
# Deletes, older than 7 days: simulation tick-cache days (only once open_window/flow/<day> exists), simulation result files,
# both bots' decision logs and daily logs; trims monitor.log to the last 7 days (bots are stopped after 16:00).
# KEEPS: code, configs, .bak backups, the data library (open_window bars/flow/bars10y/flow_tick/pm_history), reference,
# playbook library, trades, Rule Lab runs, reports/day pages.
# crontab: 30 21 * * 1-5 /usr/bin/flock -n /tmp/keep_one_week.lock /bin/sh /var/www/screener/trade/tools/keep_one_week.sh >> /var/www/screener/trade/logs/keep_one_week.log 2>&1
CUT=$(date -d "7 days ago" +%F)
S=/var/www/screener
echo "== $(date) keep files from $CUT"
pgrep -f "monitor.py" >/dev/null && { echo "a bot is running - skip"; exit 0; }
for d in "$S"/trade/data/simulations/cache/20*; do
  [ -d "$d" ] || continue; n=$(basename "$d")
  [ "$n" \< "$CUT" ] && [ -d "$S/trade/reports/open_window/flow/$n" ] && rm -rf "$d" && echo "cache $n"
done
find "$S/trade/data/simulations" -maxdepth 1 -type f ! -newermt "$CUT" -print -delete
for b in trade premarket; do
  find "$S/$b/data/decisions" -maxdepth 1 -type f -name "20*.jsonl*" ! -newermt "$CUT" -print -delete
  find "$S/$b/logs" -maxdepth 1 -type f -name "*.log*" ! -newermt "$CUT" -print -delete
  f="$S/$b/monitor.log"
  [ -f "$f" ] && awk -v c="$CUT" 'p||(substr($0,1,10)>=c && $0 ~ /^20[0-9][0-9]-/){p=1;print}' "$f" > "$f.new" && mv "$f.new" "$f"
done
df -h / | tail -1
