#!/bin/sh

set -e

image=$@

image_information=$(oras discover --artifact-type application/json "$image")
#printf "$image_information\n"
printf "Found image $image...\n"

report_digest=$(echo "$image_information" | tail -n1 | awk -F ' ' '{print $2}')
#printf "$report_digest\n"
printf "Found digests for scan report...\n"

extra_vars=""

if env | grep REGISTRY_USERNAME > /dev/null;
then
    extra_vars="$extra_vars --username $REGISTRY_USERNAME"
fi

if env | grep REGISTRY_PASSWORD > /dev/null;
then
    extra_vars="$extra_vars --password $REGISTRY_PASSWORD "
fi

image_base=$(echo "$image" | awk -F ':' '{print $1}')
printf "Pulling $image_base:@$report_digest...\n"

if [ -e result.json ]; then
    rm result.json
fi
oras pull $extra_vars $image_base:@$report_digest

if [ -e result.json ]; then
    exit 0
else
    exit 1
fi