#!/bin/bash
images="vcluster-images.tar.gz"
list="images.txt"
usage () {
    echo "USAGE: $0 [--images vcluster-images.tar.gz] --registry my.registry.com:5000"
    echo "  [-l|--image-list path] text file with list of images; one image per line."
    echo "  [-i|--images path] tar.gz generated by docker save."
    echo "  [-r|--registry registry:port] target private registry:port."
    echo "  [-h|--help] Usage message"
}

while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
        -r|--registry)
        reg="$2"
        shift # past argument
        shift # past value
        ;;
        -l|--image-list)
        list="$2"
        shift # past argument
        shift # past value
        ;;
        -i|--images)
        images="$2"
        shift # past argument
        shift # past value
        ;;
        -h|--help)
        help="true"
        shift
        ;;
        *)
        usage
        exit 1
        ;;
    esac
done
if [[ -z $reg ]]; then
    usage
    exit 1
fi
if [[ $help ]]; then
    usage
    exit 0
fi

docker load --input ${images}

linux_images=()
while IFS= read -r i; do
    [ -z "${i}" ] && continue
    [[ "${i}" == "#"* ]] && continue
    
    linux_images+=("${i}");
done < "${list}"

for i in "${linux_images[@]}"; do
    [ -z "${i}" ] && continue
    [[ "${i}" == "#"* ]] && continue

    # trim ghcr.io & registry.k8s.io & quay.io
    image_name=$(echo $i | sed 's/ghcr\.io\///')
    image_name=$(echo $image_name | sed 's/registry\.k8s\.io\///')
    image_name=$(echo $image_name | sed 's/quay\.io\///')
    image_name=$(echo $image_name | sed 's/docker\.io\///')

    echo "Push ${i} as ${reg}/${image_name}"
    docker tag "${i}" "${reg}/${image_name}"
    docker push "${reg}/${image_name}"
done
