import json
import logging
import os
import datetime
import boto3
from botocore.exceptions import ClientError

ALL_PODS_DATA_FILENAME = "all_pods_data.json"
TARGET_FILENAME = "all_pods_data.json"
BUCKET_NAME = "s3-dq-vulnerability-scanner-bucket-joels-env"
PATH = "/"
ALL_IMAGES_FILENAME="./all_image_data.json"
TRIVY_OUT_FILE_NAME="./trivy_scan_images.json"
TEMP_ALL_IMAGES_SCAN_STATUS_FILENAME = "./temp_img_scan_status.json"
REGION     = "eu-west-2"

def download_file(BUCKET_NAME, ALL_PODS_DATA_FILENAME, TARGET_FILENAME):

    # Download the file
    s3_client = boto3.client('s3')
    try:
        response = s3_client.download_file(BUCKET_NAME, ALL_PODS_DATA_FILENAME, PATH + ALL_PODS_DATA_FILENAME)
    except ClientError as e:
        logging.error(e)
        return False
    return True

download_file(BUCKET_NAME, ALL_PODS_DATA_FILENAME, PATH + ALL_PODS_DATA_FILENAME)

# def _get_images_list(ALL_PODS_DATA_FILENAME, ALL_IMAGES_FILENAME):
#
#     QUAY_REPO_NEEDLE = "quay.io"
#     QUAY_REPO_NAME = "quay"
#     ARTIFACTORY_REPO_NEEDLE = "docker.digital"
#     ARTIFACTORY_REPO_NAME = "artifactory"
#
#
#     with open(ALL_PODS_DATA_FILENAME, "r") as f:
#         pods_data = json.load(f)
#
#     all_imgs = []
#     # Build Quay Images
#     for i in pods_data.get("items"):
#         temp = {}
#         if 'Pod' in i.get("kind"):
#             for con_img in i.get("spec").get("containers"):
#                 temp["pod_name"] = i.get("metadata").get("name")
#                 temp["img_name"] = con_img.get("image")
#                 if QUAY_REPO_NEEDLE.lower() in con_img.get("image"):
#                     temp["repo_name"] = QUAY_REPO_NAME
#                 elif ARTIFACTORY_REPO_NEEDLE.lower() in con_img.get("image"):
#                      temp["repo_name"] = ARTIFACTORY_REPO_NAME
#
#         # Add image to list
#         if temp:
#             all_imgs.append( temp )
#
#     print(f"Found {len(all_imgs)} Images")
#     print(f"Successfully retrieved all images")
#
#
#     # Write to File
#     with open(ALL_IMAGES_FILENAME, "w", encoding="utf-8") as f:
#         json.dump(all_imgs, f, ensure_ascii=False, indent=4)
#
# _get_images_list(ALL_PODS_DATA_FILENAME, ALL_IMAGES_FILENAME)
#
#
# def _pull_img_to_local(ALL_IMAGES_FILENAME):
#
#     total_imgs_pulled = 0
#
#     with open(ALL_IMAGES_FILENAME, "r") as f:
#         img_data = json.load(f)
#
#     for img in img_data:
#         if img["repo_name"] == "artifactory":
#             # Authenticate
#             logging.info("Authenticating to Artifactory")
#             print("=============== Authenticating to Artifactory ================")
#             os.system("docker login docker.digital.homeoffice.gov.uk/")
#             os.system(f"docker pull {img['img_name']}")
#             total_imgs_pulled += 1
#         if img["repo_name"] == "quay":
#             os.system(f"docker pull {img['img_name']}")
#             total_imgs_pulled += 1
#
#     logging.info(f'"total_imgs_pulled":{total_imgs_pulled}')
#     print(f'"total_imgs_pulled":{total_imgs_pulled}')
#
# _pull_img_to_local(ALL_IMAGES_FILENAME)
#
#
# def _trivy_image_scanner(ALL_IMAGES_FILENAME,TRIVY_OUT_FILE_NAME):
#
#     with open(ALL_IMAGES_FILENAME, "r") as f:
#         img_data = json.load(f)
#     total_imgs_scanned = 0
#     img_scan_status = {}
#     for img in img_data:
#
#         q=img["img_name"].rsplit("/", 1)[1]
#         q=q.replace(":", "_")
#
#         # Update Tracker
#         tmp = {"pods":[],"is_scanned":False}
#         tmp["img_id"] = q
#         tmp["img_name"] = img.get("img_name")
#
#         # GET ALL PODS RUNNING THE IMAGE
#         for _p in img_data:
#             if _p.get("img_name") == img.get("img_name"):
#                 tmp["pods"].append(_p.get("pod_name"))
#
#         img_scan_status[q] = tmp
#
#     # Write to File
#     with open(TEMP_ALL_IMAGES_SCAN_STATUS_FILENAME, "w", encoding="utf-8") as f:
#         json.dump(img_scan_status, f, ensure_ascii=False, indent=4)
#
#     # BEGIN SCANNING
#     for i in img_scan_status:
#         # Trigger Scanner
#         prefix_str = "trivy --ignore-unfixed -f json -o"
#         _TRIVY_SCAN_COMMAND = f"{prefix_str} {i}.json {img_scan_status.get(i).get('img_name')}"
#         try:
#             print(f" === total_images:{len(img_scan_status)} | scanned_images: {total_imgs_scanned} | pending: {len(img_scan_status) - total_imgs_scanned } === ")
#             print(f" ==== Scanning Image: {img_scan_status.get(i).get('img_name')} ====")
#             os.system(_TRIVY_SCAN_COMMAND)
#             total_imgs_scanned += 1
#             img_scan_status[i]["is_scanned"] = True
#             img_scan_status[i]["last_scan_date"] = str(datetime.date.today())
#             print(f"=== total_images:{len(img_scan_status)} | scanned_images: {total_imgs_scanned} | pending: {len(img_scan_status) - total_imgs_scanned }")
#         except Exception as e:
#             print(f"ERROR: Unable to scan image: {img_scan_status.get(i).get('img_name')}. ERROR_MESSAGE:{str(e)}")
#
#     # Write to File
#     with open(TRIVY_OUT_FILE_NAME, "w", encoding="utf-8") as f:
#         json.dump(img_scan_status, f, ensure_ascii=False, indent=4)
#
#     print(f"Successfully scanned all Images")
#
#
# _trivy_image_scanner(ALL_IMAGES_FILENAME,TRIVY_OUT_FILE_NAME)
