#!/bin/sh
#----------------------------------------------------------------------------
# check-version - check a package-version
#
# usage: check-version package_name check_version
# or:    check-version -diff version-1 version-2
#           this version is only for list packages from eisler
#           check-version -list package_name check_version
#
# return values as output on stdout:
#
# new           - version is newer than the installed package
# old           - version is older than the installed package
# installed     - version of package is identical (installed)
# not-installed - package is not installed
#
# Creation:     2003-07-19  fm
# Last Update:  $Id: eisman_check_version.sh 42418 2016-07-21 21:22:58Z dv $
#
# Copyright (c) 2001-2016 the eisfair team, team(at)eisfair(dot)org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#----------------------------------------------------------------------------

. /var/install/include/eismanlib

new_status="new"
old_status="old"
inst_status="installed"
notinst_status="not-installed"


# setup global database path for testing
if [ -n "${EISMAN_TEST_DB}" ]
then
    EISMAN_PATH="${EISMAN_TEST_DB}"
fi


read_package_version()
{
    local package=${1}
    local result

    result=$(grep -e  "^\[.*\]\[${package}\]\[.*\]\[.*\]\[.*\]version " \
          "${EISMAN_PATH}/installed.db" |
          sed  -e 's#^\[.*\]\[.*\]\[.*\]\[.*\]\[.*\]version   *##g')

    have_package_version="${result}"
}


#-----------------------------------------------------------------------------
# main
#-----------------------------------------------------------------------------
_use_devhost=false
_use_devhost_list=false
if [ "${1}" = "-diff" ]
then
    shift
    v1=${1}
    v2=${2}

    package_status="$(diff_version ${v1} ${v2})"
else
    if [ "${1}" = "--list" ]
    then
        # for list eislist from eisler, use devhost always false
        _use_devhost_list=true
        shift
    fi

    package_name=${1}

    # special handling of kernel requirements, since it must be trans-
    # lated into it's installed variant
    if [ "${package_name}" = "eiskernel" ]
    then
        package_name=${package_name}-$(uname -r |
            awk -F'-' '{ print tolower($NF) }')
    fi

    check_version=${2}

    read_package_version "${package_name}"
    if [ -n "${have_package_version}" ]
    then
        if [ -z "${check_version}" ]
        then
            package_status="${inst_status}"
        else
            package_status="$(diff_version ${check_version} ${have_package_version})"
        fi
    else
        package_status="${notinst_status}"
    fi
fi

echo ${package_status}
