#!/usr/bin/env bash

set -euo pipefail

scan_image() {
  local image_name="$1"
  local image

  image=$(helm template "$(dirname "$0")/../../charts/komodor-agent" \
    --set apiKey=FAKEUUID-0000-1111-2222-333333333333 \
    --set clusterName=fake | awk '/image:/ {print $2}' | grep -F "${image_name}:" | sort -u) || true

  if [[ -z "$image" ]]; then
    echo "Error: Image not found: $image_name" >&2
    exit 1
  fi

  docker pull "$image"
  ./wizcli docker scan --image "$image" --group-by resource -p "komodor-agent vulnerabilities policy"
}

####################
# MAIN             #
####################

if [[ -z "${WIZ_CLIENT_ID:-}" || -z "${WIZ_CLIENT_SECRET:-}" ]]; then
  echo "Error: WIZ_CLIENT_ID and WIZ_CLIENT_SECRET must be set" >&2
  exit 1
fi

if [[ $# -lt 1 ]]; then
  echo "Usage: $0 <image_name>" >&2
  exit 1
fi

image_name="$1"

ARCH="$(uname -m)"
case "$ARCH" in
  x86_64) ARCH="amd64" ;;
  aarch64) ARCH="arm64" ;;
esac

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"

WIZCLI_URL="https://downloads.wiz.io/wizcli/latest/wizcli-${OS}-${ARCH}"
echo "Downloading wizcli from $WIZCLI_URL"
curl -fsSL -o wizcli "$WIZCLI_URL" && chmod +x wizcli

./wizcli auth --id "$WIZ_CLIENT_ID" --secret "$WIZ_CLIENT_SECRET"

komo ci docker-login

scan_image "$image_name"
