#!/usr/bin/env bash
# Copyright 2022 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o nounset
set -o pipefail

# name of the output file
OUTPUT_FILE=official-cve-feed.json

# value to return at end of script
RETURN_VALUE=0

# install python-pip3
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq python3-pip

# install requests module
pip3 install requests

# python script to generate official-cve-feed.json 
python3 fetch-official-cve-feed.py > "${OUTPUT_FILE}"
EXIT_CODE=$?
if [[ "${EXIT_CODE}" -ne 0 ]]; then
    RETURN_VALUE=${EXIT_CODE}
fi

# make the prow job logs always helpful
cat "${OUTPUT_FILE}"

# python returns 7 to indicate recoverable errors
# Exit bash script now if unrecoverable python error
if [[ "${EXIT_CODE}" -ne 0 ]] && [[ "${EXIT_CODE}" -ne 7 ]]; then
    exit "${RETURN_VALUE}"
fi

# function to calculate the hash value of official-cve-feed.json 
calculate_hash(){
    if command -v shasum >/dev/null 2>&1; then
    cat "$@" | shasum -a 256 | cut -d' ' -f1
    elif command -v sha256sum >/dev/null 2>&1; then
    cat "$@" | sha256sum | cut -d' ' -f1
    else
    echo "missing shasum tool" 1>&2
    exit 1
    fi
}

# check if official-cve-feed.json blob exists in the bucket
set -e
EXIT_CODE=0
gsutil ls "gs://k8s-cve-feed/${OUTPUT_FILE}" >/dev/null 2>&1 || EXIT_CODE=$?

# fetch the hash value of existing official-cve-feed.json json, if differs then
# upload the new cve feed data to the existing blob.
if [[ "${EXIT_CODE}" -eq 1  ]]; then 
    gsutil cp "${OUTPUT_FILE}" gs://k8s-cve-feed
    calculate_hash "${OUTPUT_FILE}" > cve-feed-hash
    echo "$(<cve-feed-hash )"
    gsutil cp cve-feed-hash gs://k8s-cve-feed
else 
    echo "Downloading the old hash blob from gcs bucket"
    gsutil cp gs://k8s-cve-feed/cve-feed-hash cve-feed-hash
    hash=$(<cve-feed-hash )
    echo "old hash value: ${hash}"
    echo "Calculate the new hash value of json feed"
    new_hash=$(calculate_hash "${OUTPUT_FILE}")
    echo "new hash value : ${new_hash}"
    echo "${new_hash}" > cve-feed-hash

    if [[  "${hash}" == "${new_hash}" ]]; then
        echo "Both the hashes have identical contents"
    else
        echo "Both the hash value differ"
        echo "Uploading the new json feed and hash value to gcs bucket"
        gsutil cp "${OUTPUT_FILE}" gs://k8s-cve-feed
        gsutil cp cve-feed-hash gs://k8s-cve-feed/cve-feed-hash
    fi
fi

exit "${RETURN_VALUE}"
