#!/bin/bash

function scan_vulnerabilities {
  # We build the Docker image for the GraphQL publishing service using a custom script. The --no-cache option ensures that the image is built from scratch without using any cached layers.
  yarn docker:build:detach
  # We save the built Docker image to a file named image.tar. The image is tagged as graphql-publishing-service:latest.
  docker save graphql-publishing-service:latest -o image.tar

  chmod a+r image.tar

  rm -rf vulnerabilities.json

  # We extract the vulnerabilities to ignore from the Jenkinsfile. This is done by searching for lines containing 'CVE', removing any single quotes and commas, and then formatting the output as a comma-separated list of CVE identifiers. The result is stored in the VULNERABILITIES_TO_IGNORE variable.
  VULNERABILITIES_TO_IGNORE=$(cat Jenkinsfile|grep 'CVE'|sed "s/'//g;s/,//g"|sed -r "s/\/\/(.*)//g"|tr -d ' '|tr '\n' ','|sed 's/.$//')

  # We run the docker image scanner with the image we just built, passing in the vulnerabilities to ignore and AWS credentials for ECR access. The output is redirected to vulnerabilities.json.
  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 -e ECR_REPOSITORY_NAME=graphql-publishing 086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-image-scanner:latest>>vulnerabilities.json 2>&1
}

function parse_output {
  # We find the line number where the "BLOCK FINDINGS" section starts in the vulnerabilities.json file. This is done using grep to search for the string and sed to extract the line number.
  LINE_TO_START=$(cat vulnerabilities.json|grep -n "BLOCK FINDINGS"|sed -r "s/:(.*)//g")

  # We use sed to remove all lines from the beginning of the file up to the line where the "BLOCK FINDINGS" section starts. The output is saved to a temporary file vulnerabilities_parsed.json.
  cat vulnerabilities.json|sed "1,${LINE_TO_START}d">vulnerabilities_parsed.json

  # We use sed again to remove any ANSI escape codes (which are used for coloring the output) from the vulnerabilities_parsed.json file. The cleaned output is saved to vulnerabilities_parsed_cleaned.json.
  cat vulnerabilities_parsed.json|sed "s/\\x1b\\[[0-9;]*m//g" > vulnerabilities_parsed_cleaned.json

  cat vulnerabilities_parsed_cleaned.json
  rm -rf vulnerabilities_parsed*.json
  rm -rf image.tar
}

scan_vulnerabilities
parse_output
