#!/bin/bash
#
# Copyright (c) 2022 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.

set -e
kubecfg="$1"
app_name="$2"
namespace="$3"

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

export KUBECONFIG="$kubecfg"

# Findout the application version if installed
function get_installed_version()
{
  # 'helm list' returns a table with following column titles
  # 'NAME   NAMESPACE  REVISION   UPDATED  STATUS  CHART   APPVERSION'
  # So, skip title row and loop through remaining rows from the output
  sudo /usr/bin/helm list --namespace "$namespace" | tail -n +2 | while read -r line
  do
    # Select CHART column (value in the format <chart_name-chart_version>)
    # so, select the 1st row matching chart_name with application name(not the 'release' name)
    # for example, 'grafana' application name, contains CHART value as 'grafana-1.2.3'
    if [[ $(echo $line|awk '{print $9}'|grep -w "$app_name"-[0-9.]*|wc -l) -gt 0 ]]; then
      # if the application found, then return its version (value of 'APPVERSION' column)
      echo "$(echo $line|awk '{print $10}')"
      break
    fi
  done
}

installed_version=$(get_installed_version)
# We only need 'a.b.c' version from 'a.b.c-x.y.z'
external_version=( ${installed_version//-/ } )
echo "${external_version[0]}"
