---
apiVersion: v1
kind: ConfigMap
metadata:
  name: watchdog-script
  namespace: spack
  labels:
    svc: watchdog
data:
  script: |
    #! /bin/bash
    filesystem_checks=("$@")
    threshold=10

    check_mem() {
      mem=($( free | grep Mem | sed 's/  */ /g' | cut -d\  -f 2,7 ))
      percent_available="$(( 100*${mem[1]}/${mem[0]} ))"
      if [ "$percent_available" -lt "$threshold" ] ; then
        echo "$( date ) - available memory below $threshold%"
      fi
    }

    check_fs() {
      fs="$1"
      percent_available=$(
        df -P "$fs" | tail -n 1 | sed 's/  */ /g' | cut -d\  -f 5 | cut -d% -f 1 )
      percent_available="$(( 100 - percent_available ))"
      if [ "$percent_available" -lt "$threshold" ] ; then
        echo "$( date ) - available space on directory below $threshold% - $fs"
      fi
    }

    check() {
      check_mem
      for fs in "${filesystem_checks[@]}" ; do
        check_fs "$fs"
      done
    }

    done=0
    trap 'done=1' EXIT INT TERM QUIT
    while [ "$done" '=' 0 ] ; do
      check
      if [ "$done" '=' 0 ] ; then sleep 15 ; fi
    done

