#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail

if ! crane version >/dev/null; then echo "Must install crane."; exit 1; fi
if ! cosign version >/dev/null; then echo "Must install cosign."; exit 1; fi

GHCR_ROOT_NAMESPACE="${GHCR_ROOT_NAMESPACE:-}"
if [ "${GHCR_ROOT_NAMESPACE}" == "" ]; then echo "Must set GHCR_ROOT_NAMESPACE."; exit 1; fi

# Convert the registry hostname to the first part of namespace
# e.g. "index.docker.io/ubuntu/mysql:8.0-20.04_beta"
# ---> "ghcr.io/<root>/index--docker--io/ubuntu/mysql:8.0-20.04_beta"
#
for img in $(cat "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/images.txt"); do
    new_img="ghcr.io/${GHCR_ROOT_NAMESPACE}"
    new_img="${new_img}/$(echo $img | cut -d/ -f1 | sed 's/\./--/g')"
    new_img="${new_img}/$(echo $img | cut -d/ -f2-)"
    crane copy "${img}" "${new_img}"
    cosign sign "${new_img}"
done