#!/bin/bash
#
# winnow.sh - monitor the execution of a large simulation set on the osg
#             and release jobs that failed over to hold for no reason,
#             stow output files that were dumped back in the submit
#             directory, and generally keep production running smoothly.
#
# author: richard.t.jones at uconn.edu
# version: march 23, 2025
#
# usage: cd <submit_dir> && winnow.sh -d

stagedir="tostow/"
outtypes="root hddm"
minsize_hddm=725000000
minsize_root=275000000

function usage() {
    echo "Usage: cd <submit_dir> && winnow.sh [-d]"
    echo " where option -d tells the script to run as a daemon in an endless loop, until interrupted by a signal."
    exit 1
}


function stow_and_go() {
    for outtype in $outtypes; do
        minsize="minsize_$outtype"
        find . -maxdepth 1 -name "*.$outtype" -size +${!minsize}c -mmin +10 -exec mv {} $stagedir \;
    done
    htgettoken.sh
    cp /run/user/7896/bt_u7896 .
    XDG_RUNTIME_DIR=/srv alma9-container scripts.d/stow.py
    scripts.d/recycle_holds.sh
}


if [ "$1" = "" ]; then
    stow_and_go
elif [ "$1" = "-d" ]; then
    while true; do
        stow_and_go
        sleep 60
    done
else
    usage
fi
