Skip to content

Instantly share code, notes, and snippets.

@wess
Created November 10, 2021 20:53
Show Gist options
  • Save wess/c19cbb51f9b8e7bda5601fb2f6757fcb to your computer and use it in GitHub Desktop.
Save wess/c19cbb51f9b8e7bda5601fb2f6757fcb to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
export SODA_SCRIPTS_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
source ${SODA_SCRIPTS_ROOT}/__echo.sh
#### Websocket Setup
SERVER_PORT=3333
WS_PIPE=/tmp/_websocket.tmp
IN_PIPE=/tmp/_in_websocket.tmp
rm -rf $WS_PIPE
mkfifo $WS_PIPE
rm -rf $IN_PIPE
mkfifo $IN_PIPE
if (( $# < 2 )); then
echo
echo "Monitor"
echo "- Usage: monitor <CMD> <FILES>"
echo "- <FILES> can also be a glob pattern"
echo
exit
fi
SILENT=0
while getopts ":s" opt; do
case $opt in
s)
SILENT=1
;;
\?)
echo "Invalid option: -$OPTARG" | error
exit
;;
esac
done
shift $(($OPTIND-1))
CMD=$1
shift
FILES=$*;
if [ $SILENT -eq 0 ]; then
echo "[monitor]: Watching files..." | status
fi
stat_opts='-f "%m"'
if [[ "$(uname)" == "Linux" ]]; then
stat_opts='-c "%Y"'
fi
CTIME=$(printf "%i" $(date "+%s"))
mtime=""
echo "Running websocket server..." | status
cat $WS_PIPE | ./scripts/__websocket.sh $IN_PIPE | nc -l $SERVER_PORT > $WS_PIPE &
serverpid=$!
trap ctrl_c INT
ctrl_c() {
kill $serverpid
exit
}
while :; do
sleep 1
for f in $(echo $FILES); do
mtime=$(eval stat $stat_opts $f)
mtime=$(printf "%i" $mtime)
if [ $? -eq 0 ]; then
if [ $mtime -gt $CTIME ]; then
CTIME=$(printf "%i" $(date "+%s"))
if [ $SILENT -eq 0 ]; then
echo '[monitor]: Retrying...' | info
echo
fi
clear
eval $CMD
echo "reload" >> $IN_PIPE
if [ $? -eq 0 ]; then
if [ $SILENT -eq 0 ]; then
echo '[monitor]: Successfully restarted $CMD' | success
fi
else
if [ $SILENT -eq 0 ]; then
echo '[monitor]: Failed to restart $CMD' | error
fi
fi
fi
else
echo "[monitor]: $f is not a file."
exit
fi
done
done
kill $serverpid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment