#
# (C) Tenable Network Security
#



function parse_pkg_name(pkg)
{
 local_var elems, num, i, name, version;
 local_var my_pkg;

 elems = split(pkg, sep:" ", keep:0);
 num = max_index(elems);
 elems = split(elems[0], sep:"-", keep:0);

 name = elems[0];

 for ( i = 1 ; i < max_index(elems) - 1 ; i ++ )
 {
 name += "-" + elems[i];
 }

 version = split(elems[i], sep:"_", keep:0);
 if ( version[0] == elems[i] ) version = split(elems[i], sep:"p", keep:0);
 if ( version[0] == elems[i] ) version = split(elems[i], sep:",", keep:0);
 
 my_pkg["name"]     = name;
 my_pkg["version"]  = version[0];
 my_pkg["revision"] = version[1];

 return my_pkg;
}


#
# Handle stuff such as "10b"
#
function convert_int(s)
{
 local_var i, ret, flag;

 flag = 0;

 for ( i = 0; i < strlen(s) ; i ++ )
 {
  if ( ord(s[i]) < ord("0") || ord(s[i]) > ord("9") ) flag = 1;
 }

 if ( flag == 0 )
	return int(s);

 ret = 0;
 for ( i = 0 ; i < strlen(s) ; i ++ )
 {
  ret *= 36;
  if ( ord(s[i]) >= ord("0") &&
       ord(s[i]) <= ord("9") ) ret += ord(s[i]);
  else
	ret += ord(tolower(s[i])) - ord("a");
 }

 return ret;
}


function vers_cmp(a, b)
{
 local_var array_a, array_b, i, max;

 array_a = split(a, sep:".", keep:0);
 array_b = split(b, sep:".", keep:0);

 max = max_index(array_a);
 if ( max_index(array_b) > max ) max = max_index(array_b);

 for ( i = 0 ; i < max ; i ++ )
 {
  if ( convert_int(s:array_a[i]) != convert_int(s:array_b[i]) )
  {
    return convert_int(s:array_a[i]) - convert_int(s:array_b[i]);
  }
 }

 return 0;
}


function pkg_cmp(pkg, reference)
{
 local_var my_pkg, my_reference, eq;

 if ( strlen(pkg) == 0 || strlen(reference) == 0) return 0;

 my_pkg = parse_pkg_name(pkg:pkg);
 my_reference = parse_pkg_name(pkg:reference);

 eq = vers_cmp(a:my_pkg["version"], b:my_reference["version"]);
 if ( eq ) return eq;
 
 if ( !isnull(my_reference["revision"]) &&
      isnull(my_pkg["revision"])  ) {
	return -1;
	}

 eq = vers_cmp(a:my_pkg["revision"], b:my_reference["revision"]);
 return eq; 
}

