#!/usr/bin/env bash

function get_available_versions {
    echo "Checking available workflow package versions..."
    mapfile -t -s 2 < <(conda search 'dag-wf*')

    # versions are reported in ascending order hence we can just iterate through 
    # them and add them to VERSIONS, which will leave us with the newest version only
    for i in "${MAPFILE[@]}"; do
        declare -a f
        readarray -t f< <(echo $i|awk '{print $1,"\n",$2,"\n",$3}'|sed 's/[ \n]//g')
        AVAILABLE[${f[0]}]="${f[1]}:${f[2]}"
    done
    return
}

function get_installed_versions {
    echo "Checking installed workflow package versions..."
    mapfile -t -s 1 < <(conda list|grep 'dag-wf')
    for i in "${MAPFILE[@]}"; do
        declare -a f
        readarray -t f< <(echo $i|awk '{print $1,"\n",$2,"\n",$3}'|sed 's/[ \n]//g')
        INSTALLED[${f[0]}]="${f[1]}:${f[2]}"
    done
    return
}

set -e
set -o pipefail

declare -A AVAILABLE
declare -A INSTALLED
declare -a NEW
declare -a UPDATED

get_installed_versions
get_available_versions

PACKAGES=($(for each in ${!AVAILABLE[@]}; do echo $each; done | sort))
OUTPUT=("PACKAGE,AVAILABLE,INSTALLED\n")
for package in ${PACKAGES[*]};do
    if [[ -z "${INSTALLED[$package]}" ]]; then
        NEW+=( "${package}" )
    elif [[ "${AVAILABLE[$package]}" != "${INSTALLED[$package]}" ]]; then
        UPDATED+=( "${package}" )
    fi
    OUTPUT+="$package,${AVAILABLE[$package]},${INSTALLED[$package]}\n"
done

echo
echo -e ${OUTPUT[@]}|sed 's/,/,|,/g'|column -s ',' -t
echo

if [ "${#NEW[@]}" -gt 0 ]; then
    echo "The following new packages are available:"
    for package in "${NEW[@]}"; do
        echo -e "\t* $package"
    done
    echo
fi

if [ "${#UPDATED[@]}" -gt 0 ]; then
    echo "Updates are available for the following packages:"
    for package in "${UPDATED[@]}"; do
        echo -e "\t* $package"
    done
    echo
fi

echo "Run 'conda update dag-wf' to update to the latest versions"
echo
