#!/bin/bash
export TEXTDOMAINDIR='/usr/share/locale'
export TEXTDOMAIN='podsec-inotify'

export EVENTS="moved_from,create,delete,modify"
export OVERLAYDIRS="/tmp/inotifyOverlays.tmp"
export MONITORDIRS="/tmp/inotifyMonitor.tmp"
export ERRLOGFILE="/tmp/inotifyError.tmp"

export ROOTFUL_CONTAINERS="/var/lib/containers/storage/overlay"
export PROGNAME=$(basename $0)

# Set max watches files
echo 1048576  > /proc/sys/fs/inotify/max_user_watches

get_monitor_dirs() {
  ls -1d $ROOTFUL_CONTAINERS\
  /home\
  /home/*/.local/share/\
  /home/*/.local/share/containers/storage/overlay/ \
  /var/lib/u7s-admin/.local/share/usernetes/containers/storage/overlay/
}

# Create file with all rootless overlays
get_overlays () {
  dirs=$(ls -1d \
    $ROOTFUL_CONTAINERS/*/diff \
    /home/*/.local/share/containers/storage/overlay/*/diff \
    /var/lib/u7s-admin/.local/share/usernetes/containers/storage/overlay/*/diff
    )
  for dir in $dirs
  do
    echo $dir
    for exclude in var proc tmp run
    do
      echo "@$dir/$exclude"
    done
  done
}

get_overlays > $OVERLAYDIRS
get_monitor_dirs > $MONITORDIRS
(
set -o pipefail
while :;
do
  inotifywait -q --event "$EVENTS" --fromfile $MONITORDIRS  >/dev/null
  get_overlays > $OVERLAYDIRS
  get_monitor_dirs > $MONITORDIRS
  fuser -vk $ERRLOGFILE
done
) &

logevent() {
  file=$1
  event=$2
  dir=$3
  # echo "FILE=$file EVENT=$event DIR=$dir"
  ifs=$IFS IFS=/
  set -- $dir
  IFS=$ifs
  while [ $# -gt 2 -a "$2" != 'diff' ]; do shift; done
  container=$1
  shift; shift
  dir=
  while [ $# -gt 0 ]
  do
    dir+="/$1"
    shift
  done
  dir+='/'
  # echo "CONTAINER=$container DIR=$dir"
  homedir=${dir:0:6}
  priority=5
  if [ "$homedir" = '/home/' -o "$homedir" = '/root/' ]
  then
    mes="$(gettext 'in home directory')"
    prefix='Warning'
  elif [ "${dir:0:5}" = '/etc/' ]
  then
    mes="$(gettext 'in configuration directory')"
    prefix='Warning'
  else
    mes=''
    priority=2
    prefix='Critical'
  fi
  File="$dir$file"
  message="$(gettext 'An event') $event $(gettext 'occurred in the container') $container $mes $(gettext 'on the file') $File"
  logger -p $priority -t "${PROGNAME}" "$prefix: $message"
}

set -o pipefail
while :;
do
#  -t 10 \
  inotifywait -q -m --recursive \
    --event "$EVENTS"  \
    --fromfile $OVERLAYDIRS \
    --format "'%f' '%e'  '%w'" 2>$ERRLOGFILE |
    (
    while read str
    do
      eval logevent $str
    done
    )
done
