#!/bin/bash

set -e

###############################################
###
### read lib
###

canonicalname(){
	if test $# -ne 1; then
		echo Usage: canonicalname path >&2
		return 1
	fi
	file="$1"
	if test ! -e "$file"; then
		echo $file: file not found >&2
		return 1
	fi
    # if this is a symlink, then follow the symlink
	if test -L "$file"; then
		fdir="`dirname \"$file\"`"
		flink="`readlink \"$file\"`"
		if test -e "$flink"; then
			# these are absolute links, or links in the CWD
			canonicalname "$flink"
		else
			canonicalname "$fdir/$flink"
		fi
	else
        # if this is a file, then remember the filename and
        # canonicalize the directory name
		if test -f "$file"; then
			fdir="`dirname \"$file\"`"
			fname="`basename \"$file\"`"
			fdir="`canonicalname \"$fdir\"`"
			echo "$fdir/$fname"
		fi
        # if this is a directory, then create an absolute 
        # directory name and we are done
		if test -d "$file"; then
			(cd "$file"; pwd)
		fi
	fi
}

canonicalpath(){
  if test $# -ne 1; then
     echo Usage: canonicalpath path >&2
     return 1
  fi
  dirname $(canonicalname "$1")
}

checkdebug () {
  while test $# -gt 0; do
    if test x$1 = x--debug; then
      echo yes
      return
    fi
    shift
  done
  echo no
}

DEBUG=`checkdebug $@`
if test "x$DEBUG" = "xyes"; then
  set -x
  set -v
fi

export COMMAND_DIR="`canonicalpath $0`"

# Read the modules find part
. "$COMMAND_DIR/dunemodules.inc"

#
# test version checks
#

test_version_check () {
  if ! check_version "$1" "$2"; then
    echo "ERROR: version does not match (found $1, required $2)" >&2
    #exit 1
  else
    echo "OK:    version does match     (found $1, required $2)" >&2
  fi
}

test_version_check "1.2.3" ">= 1.2.5 || < 1.2.4"
test_version_check "1.2.4" ">= 1.2.5 || < 1.2.4"
test_version_check "1.2.5" ">= 1.2.5 || < 1.2.4"
test_version_check "1.2" ">= 1.2.5 || < 1.2.4"

test_version_check "1.2.3" ">= 1.2.5 && < 1.2.4"
test_version_check "1.2.4" "< 1.2.5 && >= 1.2.4"

test_version_check "1.2.3" ">= 1.2"
test_version_check "1.2.3" "= 2.4.1"
test_version_check "1.2.3" "= 1.2.3"
test_version_check "1.2.3" "> 1.2"
test_version_check "1.2.3" "= 1.2"
test_version_check "1.2.3" "< 1.2"

check_pattern()
{
  PATTERN=$PARSE_SUGDEP_PATTERN
}

parse_version()
{
  local deps="$1"
  local name=""
  local dep=""
  local xdeps=""
  echo start: $deps
  while test -n "$deps"; do
    PATTERN=$PARSE_SUGDEP_PATTERN
    name=`echo $deps | sed -e "s/$PATTERN/\1/"`
    ver=`echo $deps | sed -e "s/$PATTERN/\2/" -e 's/[()]//g'`
    xdeps=`echo $deps | sed -e "s/$PATTERN/\3/"`
    if test "$deps" = "$xdeps"; then
      echo Error parsing dependency string \"$1\"
	  exit 1
    fi
    deps=$xdeps
    echo $name version $ver ... $deps
  done
  echo done
}

parse_version "dune-common (>= 1.2), dune-istl (<999)"
parse_version "alf (12) bart()c"
parse_version "a b () c"
