#This will trigger a named CloudBuild if a CVE fix
#has been detected for the named container

import base64
import json
import os

from google.cloud.devtools import containeranalysis_v1
from google.cloud.devtools import cloudbuild_v1

registry = "bookshelf"
project_id = "enterprisedemos-258322"
trigger_id = "CVE-fix-rebuild"

def cve_trigger(event, context):
    """Triggered from a message on a Cloud Pub/Sub topic.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    pubsub_message = json.loads(base64.b64decode(event['data']).decode('utf-8'))
    print(pubsub_message)
    
    if "VULNERABILITY" in pubsub_message['kind']:
        occurrence_id = os.path.basename(pubsub_message['name'])

        client = containeranalysis_v1.ContainerAnalysisClient()
        grafeas_client = client.get_grafeas_client()
        parent = grafeas_client.occurrence_path(project_id, occurrence_id)
        occurrence = grafeas_client.get_occurrence(parent)
        if registry in occurrence.resource_uri:
            for i in occurrence.vulnerability.package_issue:
                if i.fixed_package is not None:
                    print("Fix found.  Triggering build.")
                    buildsomething = cloudbuild_v1.CloudBuildClient()
                    buildsomething.run_build_trigger(project_id, trigger_id, {})

