#!/bin/bash
#
# Copyright (c) 2023 Oracle and/or its affiliates. All rights reserved.
# Licensed under the GNU General Public License Version 3 as shown at https://www.gnu.org/licenses/gpl-3.0.txt.

# Metallb has a tool to convert ConfigMap to CustomResource.
# We allow usage of ConfigMaps for backward compatibility.
# Upgrading from v0.12.1 which uses ConfigMaps to v0.13.x,
# we need to convert the ConfigMap to CustomResource.
# The tool that metallb provides is an image and this is the recommended way
# to run the tool from metallb site.
# Refer: https://metallb.universe.tf/configuration/migration_to_crds/
# We use podman since that is what is available in the environment

image_whitelist="configmaptocrs"
tag_whitelist="0.13.9 0.13.10"

source=$1
imageUrl=$2
version=$3

# version will be like v0.13.10-1 which is the image tag
# We need to get only the version so we can check whitelist versions
version1="${version:1}"
version1=${version1%-*}

if ! echo "$2" | grep -w "$image_whitelist"; then
      echo "$2 image is not permitted to be run in this script" 1>&2
      exit 1
fi
if ! echo "$tag_whitelist" | grep -w "$version1"; then
      echo "$3 version is invalid" 1>&2
      exit 1
fi
sourceFile=`basename $source`
dirName="$(dirname $source)"
IMAGE=$imageUrl":"$version
podman image exists ${IMAGE} || crictl pull ${IMAGE}
podman --storage-opt ignore_chown_errors=true run -d -v $dirName:/var/input ${IMAGE} --source $sourceFile
if [ $? -ne 0 ]; then
        echo "metallb configmaptocrs tool failed" 1>&2
        failed=true
fi
ctrid=$(podman ps -a | grep configmaptocrs | awk '{ print $1 }')
podman rm $ctrid

if [ $failed ]; then
    exit 1
fi