snippets/cron-limiter/crolim

60 lines
1.5 KiB
Plaintext
Raw Normal View History

2022-03-10 06:32:44 +00:00
#!/bin/bash
VERBOSE=0
CONFIG_DIR=$HOME/.config/crolim
MEMORY_FILE=${CONFIG_DIR}/memory
STATUS_COMMAND="date +%D"
function usage() {
echo "Usage: $0 [OPTIONS] COMMAND"
echo " $0 -h"
echo ""
echo " -h ... show help"
echo ""
echo " OPTIONS"
echo " -m --memory-file ... location to store previous status value"
echo " -s --status-command ... command to execute to get the current status"
echo " -v --verbose ... verbose mode"
echo " COMMAND ... command to limit until memory and status are the same"
}
# read the options
TEMP=`getopt -o m:s:hv --long memory-file:,status-command:,help,verbose -- "$@"`
eval set -- "$TEMP"
while true ; do
case "$1" in
-h | --help) usage; exit 0
;;
-v | --verbose) VERBOSE=1 ; shift
;;
-m | --memory-file)
MEMORY_FILE=$2 ; shift 2
;;
-s | --status-command)
STATUS_COMMAND=$2 ; shift 2
;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
# check limiting condition
#mkdir -p `dirname $MEMORY_FILE`
STATUS_NOW=`eval $STATUS_COMMAND`
STATUS_MEMORY=""
if [[ -f $MEMORY_FILE ]]; then
STATUS_MEMORY=`cat $MEMORY_FILE`
fi
if [[ "$STATUS_NOW" == "$STATUS_MEMORY" ]]; then
[[ $VERBOSE == 1 ]] && echo "Limiting, status is the same: ${STATUS_NOW}"
exit 0
else
[[ $VERBOSE == 1 ]] && echo "Status changed from '${STATUS_MEMORY}' to '${STATUS_NOW}'"
echo ${STATUS_NOW} > $MEMORY_FILE || { echo "Cannot update memory file: $MEMORY_FILE" ; exit 1 ; }
fi
# run the command!
eval $@