#!/bin/bash

###########################################################
# Docker Image Build and Push Script
# Author: Brandon McClure
# Description: This script builds a Docker image based on
#              the CI environment and pushes it to
#              specified Docker registries based on
#              configuration settings.
# License: This code was hobbled together using knowledge 
#          from many other people and even some ChatGPT. 
#          I am licensing what I am able to as [WTFPL](http://www.wtfpl.net/txt/copying/)
###########################################################

set -e

# Check if CI environment variables are set
if [ -z "$CI_COMMIT_REF_NAME" ] || [ -z "$CI_DEFAULT_BRANCH" ] || [ -z "$CI_COMMIT_REF_SLUG" ] || [ -z "$DOCKER_IMAGE_NAME" ]; then
    echo "Error: Required CI environment variables are not set."
    echo "Please make sure to run this script in your CI environment or set the necessary variables before running locally."
    exit 1
fi

docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY

declare -A registries1=(
[reg_slug]=registry.gitlab.com/matrix-rss-bridge
[push]=true
[tar]=false
)

DOCKER_IMAGE_NAME_TRIMMED="$(echo -e "${DOCKER_IMAGE_NAME}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
DOCKER_REGISTRIES=("${!registries@}")
declare -n arr_ref

if [[ "$CI_COMMIT_REF_NAME" == "$CI_DEFAULT_BRANCH" ]]; then
    tags="$CI_DEFAULT_BRANCH,latest"
    echo "Running on default branch '$CI_COMMIT_REF_NAME': tags = '$tags'"
else
    tags="$CI_COMMIT_REF_SLUG,latest"
    echo "Running on branch '$CI_COMMIT_REF_SLUG': tags = $tags"
fi

tag_array=$(echo $tags | tr "," "\n")
# https://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-a-bash-variable

registry_slug_array=$(echo $DOCKER_REGISTRIES | tr "," "\n")
for arr_ref in "${DOCKER_REGISTRIES[@]}"; do
    thisRef=${arr_ref[reg_slug]}
    regSlug="$(echo -e "${thisRef}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    for tag in $tag_array; do
        docker_tags="$docker_tags -t ${regSlug}/${DOCKER_IMAGE_NAME_TRIMMED}:${tag}"
    done
done

echo "docker build --pull $docker_tags ."
docker build --pull $docker_tags .

for arr_ref in "${DOCKER_REGISTRIES[@]}"; do
    thisRef=${arr_ref[reg_slug]}
    regSlug="$(echo -e "${thisRef}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    if [[ ${arr_ref[push]} == "true" ]]; then   
        echo "pushing for ${regSlug}"
        for tag in $tag_array; do
            docker push "${regSlug}/${DOCKER_IMAGE_NAME_TRIMMED}:${tag}"
        done
    fi
    if [[ ${arr_ref[tar]} == "true" ]]; then

        echo "saving tar file for ${regSlug}"
        for tag in $tag_array; do
            docker save "${regSlug}/${DOCKER_IMAGE_NAME_TRIMMED}:${tag}" -o "${DOCKER_IMAGE_NAME_TRIMMED}_${tag}.tar"
        done
    fi 
done