#!/bin/sh

# Copyright 2023 Consolinno Energy GmbH
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http:#www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.

# Script which login to docker registry, according to the "docker_registry" key,

if [ $# -ne 1 ]; then
    echo "Must be invoked with exactly one argument: The JSON configuration." 1>&2
    exit 2
fi

CONFIG="$1"

if ! [ -e "$CONFIG" ]; then
    echo "Error: $CONFIG does not exist." 1>&2
    # exit silently if no config exists
    exit 0
fi

# get docker registry login data from env
docker_registry="$(jq -r -e .docker_registry < "$CONFIG")"
return_code_reg=$?
# if return core reg is not 0, then exit
if [ $return_code_reg -ne 0 ]; then
    echo "Info: docker_registry not found in $CONFIG" 1>&2
    exit 0
fi
docker_registry_username="$(jq -r -e .docker_registry_username < "$CONFIG")"
return_code_user=$?
# if return core reg is not 0, then exit
if [ $return_code_user -ne 0 ]; then
    echo "Info: docker_registry_username not found in $CONFIG" 1>&2
    exit 0
fi
docker_registry_password="$(jq -r -e .docker_registry_password < "$CONFIG")"
return_code_pass=$?
# if return_code_pass is not 0, then exit
if [ $return_code_pass -ne 0 ]; then
    echo "Info: docker_registry_password not found in $CONFIG" 1>&2
    exit 0
fi

# if return_code_reg, return_code_user and return_code_pass equals 0, then login to docker registry
if [ $return_code_reg -eq 0 ] && [ $return_code_user -eq 0 ] && [ $return_code_pass -eq 0 ]; then
    docker login -u "$docker_registry_username" -p "$docker_registry_password" "$docker_registry"
    exit $?
fi
# else return 0
exit 0
