#!/bin/bash

# set environment variable for distribution scritps
export RUN_MAIN_INSTALLER=1

csc_vercmp() 
{
    ver_from="${1:?missing from-version}"
    ver_to="${2:?missing to-version}"

    if [ "$ver_from" = "$ver_to" ]; then
        echo same
    else
        ver_min="$(printf '%s\n' "$ver_from" "$ver_to" | sort -V | head -n1)"
        if [ "$ver_min" = "$ver_from" ]; then
            echo older
        else
            echo newer
        fi
    fi
}

dist=`grep DISTRIB_ID /etc/*-release | awk -F '=' '{print $2}'`

if [ -f /opt/acnvm/bin/acnvmcollector ]; then

    if /opt/acnvm/bin/acnvmcollector -v > /dev/null 2>&1; then

        installed_version=$(/opt/acnvm/bin/acnvmcollector -v | sed -n 's/.*version \([^ ]*\).*/\1/p')
        installing_version=$(./acnvmcollector -v | sed -n 's/.*version \([^ ]*\).*/\1/p')

        if [ $installed_version = "$installing_version" ]; then
                echo "Collector with same version already installed."
                exit 1
        else
                existing_ver="$(csc_vercmp "$installed_version" "$installing_version")"
                if [ "$existing_ver" != older ]; then
                    echo "Collector with higher version already installed."
                    exit 1
                else
                    echo "Upgrading Collector from $installed_version to $installing_version"
                fi
        fi
    fi
fi


if [ "$dist" = "Ubuntu" ]; then
  sh ./install_ubuntu.sh
else
  sh ./install_centos.sh
fi

# unset the environment variable
unset RUN_MAIN_INSTALLER