#!/bin/bash
#
# Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved.
# Licensed under the GNU General Public License Version 2 as shown at https://oss.oracle.com/licenses/GPL-2.

set -e
kubecfg="$1"
showall="$2"

# Returns not found so we can mark the resource as uninstalled
if [ ! -f /usr/local/bin/istioctl ]; then
    echo "istioctl not found" >> /dev/stderr
    exit 1
fi

export KUBECONFIG="$kubecfg"

installed_version=$(/usr/local/bin/istioctl version)

if [ "${showall}" == "true" ]; then
    echo "${installed_version}"
else
    filtered_version=$(echo "${installed_version}" | grep "control plane version" | head -1| cut -d':' -f2)
    # We only need 'a.b.c' version from 'a.b.c-x.y.z'
    external_version=( ${filtered_version//-/ } )
    echo "${external_version[0]}"
fi
