#!/bin/bash

function scan_vulnerabilities {
  GITHUB_TOKEN=$GITHUB_NPM_TOKEN docker compose build --no-cache function

  LAMBDA=$(pwd|sed -r "s/(.*)lambda\///g")
  docker save ${LAMBDA}-function:latest -o image.tar

  chmod a+r image.tar

  rm -rf vulnerabilities.json

  VULNERABILITIES_TO_IGNORE=$(cat ../../Jenkinsfile|grep 'CVE'|sed "s/'//g;s/,//g"|sed -r "s/\/\/(.*)//g"|tr -d ' '|tr '\n' ','|sed 's/.$//')

  docker run --rm --pull always -v ./image.tar:/var/app/image.tar -e VULNERABILITIES_TO_IGNORE=$VULNERABILITIES_TO_IGNORE -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_SESSION_TOKEN 086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-image-scanner:latest>>vulnerabilities.json 2>&1
}

function parse_output {
  LINE_TO_START=$(cat vulnerabilities.json|grep -n "BLOCK FINDINGS"|sed -r "s/:(.*)//g")

  cat vulnerabilities.json|sed "1,${LINE_TO_START}d">vulnerabilities_tmp.json

  cat vulnerabilities_tmp.json|sed "s/\\x1b\\[[0-9;]*m//g" > vulnerabilities.json
  mv vulnerabilities_tmp.json vulnerabilities.json

  rm -rf vulnerabilities_tmp.json
  rm -rf image.tar
  cat vulnerabilities.json
}

scan_vulnerabilities
parse_output
