#!/bin/bash

# Load images from a Wallaroo airgap release into a generic image registry. Also emits "image-values.yaml".

set -euo pipefail

PROG=load-images
app_version=''
repl_license=''
repl_username=''
load_image=''

dryrun=${DRYRUN:-false}

die() {
    echo "$PROG: $*" >&2
    exit 1
}

usage() {
    echo "$@" >&2
    echo >&2
    echo 'USAGE: load-images ARGUMENTS...

Required Arguments
  --wallaroo-version VERSION       Wallaroo product version (with no v).  Example: 2024.4.0
  --wallaroo-license LICENSE       Wallaroo license ID: a 28-character string.
  --wallaroo-username USERNAME     Wallaroo username: Typically an email address.
  --registry-namespace NAMESPACE   Desired namespace in private registry. Often "wallaroo".
  --registry-host HOST             Hostname and port of private registry.

Optional Arguments
  --load-image IMAGE_URI           Load only this one image instead of all the Wallaroo ones
' >&2
    exit 1
}

command -v curl &> /dev/null	|| die "'curl' must be installed"
command -v docker &> /dev/null	|| die "'docker' must be installed"
command -v jq &> /dev/null	|| die "'jq' must be installed"

if $dryrun; then
    docker() { echo docker "$@"; }
fi

while [ $# -gt 0 ]; do
    case "$1" in
	--wallaroo-version)    app_version=$2; shift 2;;
	--wallaroo-license)    repl_license=$2; shift 2;;
	--wallaroo-username)   repl_username=$2; shift 2;;
	--registry-namespace)  registry_namespace=$2; shift 2;;
	--registry-host)       registry_host=$2; shift 2;;
	--load-image)          load_image=$2; shift 2;;
	*) usage "unknown argument $1";;
    esac
done

[[ -n "$repl_license" ]]	|| usage "missing argument --license"
[[ -n "$repl_username" ]]	|| usage "missing argument --username"
[[ -n "$app_version" ]]		|| usage "missing argument --version"
[[ -n "$registry_namespace" ]]	|| usage "missing argument --registry-namespace"
[[ -n "$registry_host" ]]	|| usage "missing argument --registry-host"

case $app_version in
    v*) usage "Do not include the 'v' in --version string";;
    *) ;;
esac

echo "$repl_license" | docker login proxy.replicated.com -u "$repl_username" --password-stdin 

load-image()
{
    local img="$1"
    
    # Bare repo name without host and tag
    local repo=${img##*/}
    repo=wallaroo/${repo%:*}

    # New full repo name and tag
    local new_repo=${registry_host}/${registry_namespace}/${img##*/}

    # just the tag
    local tag=${img/#*:/}

    echo "loading $repo:$tag"

    # Why not pull images directly from their home registries? We maximize the use of the replicated
    # proxy in order to reduce the number of hostnames we need to get egress privileges at customer
    # site.

    case "$img" in
	ghcr.io/wallaroolabs/*) img="proxy.replicated.com/proxy/wallaroo/$img";;

	# docker.io/foo:123 should be just foo:123 through the proxy
	docker.io/*) img="proxy.replicated.com/proxy/anonymous/$(basename "$img")";;

	# Just pull the image directly. This host is unsupported by replicated proxy.
	cr.fluentbit.io/*) ;;
	nvcr.io/*) ;;
	registry.k8s.io/*) ;;

	# Supported by the proxy, use that
	*) img="proxy.replicated.com/anonymous/$img";;
    esac

    docker pull -q "$img"
    docker tag "$img" "$new_repo"
    docker push -q "$new_repo"
}

# Generate a Helm values yaml file which overrides all the Wallaroo images in order to use a private image registry.
emit-image-values() {
    local registry=${registry_host}/${registry_namespace}

    cat <<EOF > image-values.yaml
# This file was automatically generated by Wallaroo generate-airgap-image-values containing
# Helm values to override third party images when installing with a private container registry.
# This should be regenerated using the new generator if upgrading.

kubectl:
  image:
    repository: $registry/kubectl

minio:
  imagePullSecrets:
    - name: regcred
  image:
    repository: $registry/minio
  mcImage:
    repository: $registry/mc

nats:
  global:
    image:
      pullSecretNames:
        - regcred
      registry: $registry

  reloader:
    enabled: true
    image:
      repository: nats-server-config-reloader
  
natsBox:
  container:
    image:
      repository: $registry/nats-box

spireAgentInit:
  image: $registry/wait-for-it:latest

fluent-bit:
  imagePullSecrets:
    - name: regcred
  image:
    repository: $registry/fluent-bit
  testFramework:
    image:
      repository: $registry/busybox
      tag: 1.36
EOF
}    

if [[ "$load_image" ]]; then
    echo "Loading only $load_image"
    load-image "$load_image"
else
    echo Loading all Wallaroo images

    # Replicated images
    curl -s -H "Authorization: $repl_license" "https://replicated.app/v3/app/wallaroo/images?version=$app_version" |
	jq -r '.[] | .image' |
	while read -r img; do
	    load-image "$img"
	done

    echo Emitting image-values.yaml
    emit-image-values
fi
