#!/usr/bin/env bash

set -Eeuo pipefail

isRollback=false
container_registry=''

parseParams() {
    while :; do
        case "${1-}" in
        --rollback) isRollback=true ;;
        -c | --container-registry)
            container_registry="${2-}"
            shift
            ;;
        -?*) ./lib/die.sh "Unknown option: $1" ;;
        *) break ;;
        esac
        shift
    done

    if [[ -z $container_registry ]] ; then
        ./lib/die.sh "The container-registry must be set"
    fi
}

login() {
    loginCommand=""
    if [[ $1 == *.azurecr.io ]] ; then
        loginCommand="az acr login --name ${1%".azurecr.io"}"
        else
        loginCommand="docker login $1"
    fi

    ./lib/msg.sh "Logging into registry $1"
    eval "$loginCommand"
}

upgradeImages() {
    source_registry="$(lib/yq_linux_amd64 'e' '.source-registry' 'lib/config.yaml')"
    source_image_prefix="$(lib/yq_linux_amd64 'e' '.source-registry-image-prefix' 'lib/config.yaml')"
    image_prefix="$(lib/yq_linux_amd64 'e' '.image-prefix' 'lib/config.yaml')"

   login "$source_registry"
   login "$container_registry"

    images=$(lib/yq_linux_amd64 'e' '.versions' 'lib/config.yaml')
    echo "$images" | while IFS= read -r line ; do
        name=$( echo "$line" | cut -d ':' -f 1 )
        version=$( echo "$line" | cut -d ':' -f 2 | xargs )

        source_image="$source_registry/$source_image_prefix/$name:$version"
        target_image="$container_registry/$image_prefix/$name:$version"
        target_image_latest="$container_registry/$image_prefix/$name:latest"

        ./lib/msg.sh "pulling $source_image"
        docker pull $source_image
        docker tag $source_image $target_image
        ./lib/msg.sh "Pushing it as $target_image"
        docker push $target_image
        docker tag $source_image $target_image_latest
        ./lib/msg.sh "Also pushing it as $target_image_latest"
        docker push $target_image_latest
    done
}

main() {
    parseParams "$@"

    ./lib/msg.sh ""
    ./lib/msg.sh "-------- Pushing images to $container_registry ---------"

    if [[ $isRollback == true ]]; then
        ./lib/msg.sh "This step can not be rolled back, pushed docker images will not be deleted from the container registry."
        return
    fi

    ./lib/msg.sh "This part of the script upgrades the images, meaning that it will pull images from $(lib/yq_linux_amd64 'e' '.source-registry' 'lib/config.yaml') and push"
    ./lib/msg.sh "them to $container_registry. They will also pushed tagged as 'latest'. Note that this step can not be rolled back."

    read -p "Upgrade images? [y/n]" -n 1 -r
    printf '\n'
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        return
    fi

    upgradeImages
    ./lib/msg.sh "Pushed all images to $container_registry."
}

main "$@"
