#!/bin/bash
#
# grypescan
#
# bob.nutter@manchester.ac.uk
#

VER=0.3

HOST=$(hostname -f)
TMPDIR=/tmp/grype.$$

EMAIL=pete.bradley@manchester.ac.uk

if [ "$1" = "-h" -o "$1" = "--help" ]; then
    echo "Usage: $(basename $0) searchdir"
    exit 1
fi

# search all local filesystems by defualt else arg1
SEARCH=${1-/}

# quick 'n' dirty test for apt or yum
if command -v yum >& /dev/null ; then PKGCMD=yum ;fi
if command -v apt-get >& /dev/null ; then PKGCMD=apt-get ;fi

# got curl?
if ! command -v curl >& /dev/null ; then
    echo "[WARN] curl command doesn't exist, installing it via $PKGCMD!"
    $PKGCMD -y -q install curl >/dev/null
    #exit 1
fi

# got mutt?
if ! command -v mutt >& /dev/null ; then
    echo "[WARN] mutt command doesn't exist, installing it via $PKGCMD!"
    $PKGCMD -y -q install mutt >/dev/null
    #exit 1
fi


mkdir $TMPDIR
echo ""
echo "$(basename $0) v$VER [$(date)]"
echo ============

# get latest version of grype
echo "[INFO] getting latest version of grype..."
export https_proxy=http://proxy.man.ac.uk:3128/
curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin

# get war/jar locations on local disks only, extract the first dir and run grype on each
[ "$SEARCH" = "/" ] && echo "[INFO] scanning local filesystems for war/jar files..." \
		    || echo "[INFO] scanning $SEARCH for war/jar files..."	     
for i in $(find $SEARCH -mount -iname  '*.jar' -or -iname '*.war'|cut -d/ -f2|sort -u); do
    echo "[INFO] found war/jar in $i, running grype..."
    /usr/local/bin/grype dir:/$i -s AllLayers -o json --file $TMPDIR/$HOST.$i.json
done

for i in $(ls $TMPDIR) ; do
    echo "[INFO] mailing $i to $EMAIL & root..."
    echo "See attachment for JSON file..."  |mutt -s "[grypescan] results for $i" $EMAIL,root -a $TMPDIR/$i
done
