#!/bin/bash
# Функция возвращает список образов в кеше podman rootfull
export TEXTDOMAINDIR='/usr/share/locale'
export TEXTDOMAIN='podsec-inotify'

export U7S_TRIVY_SERVER

source podsec-inotify-functions
getTrivyServer

getimagelist() {
  podman images --format="{{.Repository}}:{{.Tag}}"
}

trivyUserImages() {
  user=$1
  shift
  for image
  do
    message=$(trivyCheckImage $PROGNAME $image )
    if [ "$?" -gt 0  -a -n "$MAILTO" ]
    then
      echo "$message" |
      mail -s "$(gettext 'Vulnerabilities found in image') $image $(gettext 'of user') $user" "$MAILTO"
    fi
  done
}

export PROGNAME=$(basename $0)
export MAILTO=
if [ $# -ge 2 ]
then
  if [ "$1" = '-m' ]
  then
    MAILTO=$2
  fi
fi

if [ "$(id -u)" -eq 0 ]
then
  imagesJSON='/var/lib/containers/storage/overlay-images/images.json'
  if [ -f "$imagesJSON" ]
  then
    images=$(jq -r '.[].names[]' $imagesJSON)
    prog=$(which $0)
    trivyUserImages root $images
  fi
  imagesJSONs="
  .local/share/containers/storage/overlay-images/images.json
  "
  prog=$(which $0)
  awk -F: '$0=$1" "$6' /etc/passwd |
  while read user homeDir
  do
    if [ -z "$user" ]; then continue; fi
    for imagesJSON in $imagesJSONs
    do
      if [ -f "$homeDir/$imagesJSON" ]
      then
        machinectl -q shell ${user}@ $prog </dev/null
        break
      fi
    done
  done
else
  user=$(id -u -n)
  imagesJSONs="
  $HOME/.local/share/containers/storage/overlay-images/images.json
  $HOME/.local/share/usernetes/containers/storage/overlay-images/images.json
  "
  for imagesJSON in $imagesJSONs
  do
    if [ -f $imagesJSON ]
    then
      images=$(jq -r '.[].names[]' $imagesJSON)
      trivyUserImages "$user" $images
    fi
  done
fi
exit 0

