#! /bin/sh

test -f /bin/ksh && test -z "$RUNNING_KSH" \
  && { UNAMES=`uname -s`; test "x$UNAMES" = xULTRIX; } 2>/dev/null \
  && { RUNNING_KSH=true; export RUNNING_KSH; exec /bin/ksh $0 ${1+"$@"}; }
unset RUNNING_KSH

# No failure shall remain unpunished.
set -e

me=$(basename "$0")
medir=$(dirname "$0")

# We have to initialize IFS to space tab newline since we save and
# restore IFS and apparently POSIX allows stupid/broken behavior with
# empty-but-set IFS.
# http://lists.gnu.org/archive/html/automake-patches/2006-05/msg00008.html
# We need space, tab and new line, in precisely that order.  And don't
# leave trailing blanks.
space=' '
tab='	'
newline='
'
IFS="$space$tab$newline"

# Pacify verbose cds.
CDPATH=${ZSH_VERSION+.}$path_sep

# In case someone crazy insists on using grep -E.
: ${EGREP=egrep}

debug=false
quiet=false     # by default let the tools' message be displayed
verb=false      # true for verbose mode

## --------------------- ##
## Auxiliary functions.  ##
## --------------------- ##

# In case `local' is not supported by the shell.
(
  foo=bar
  test_local () {
    local foo="foo"
  }
  test_local
  test $foo = bar
) || local () {
  case $1 in
    *=*) eval "$1";;
  esac
}


# stderr LINE1 LINE2...
# ---------------------
# Report some information on stderr.
stderr ()
{
  for i
  do
    echo >&2 "$me: $i"
  done
}

# verbose WORD1 WORD2
# -------------------
# Report some verbose information.
verbose ()
{
  if $verb; then
    stderr "$@"
  fi
}

# run COMMAND-LINE
# ----------------
# Run the COMMAND-LINE verbosely, and catching errors as failures.
run ()
{
  if $verb; then
    first=true
    for i
    do
      if $first; then
	stderr "Running: $i"
	first=false
      else
	stderr "       : $i"
      fi
    done
  fi
  "$@" 1>&5 ||
     error 1 "$1 failed"
}


# error EXIT_STATUS LINE1 LINE2...
# --------------------------------
# Report an error and exit with EXIT_STATUS.
error ()
{
  local s="$1"
  shift
  stderr "$@"
  exit $s
}


# fata LINE1 LINE2...
# -------------------
# Report an error and exit 1.
fatal ()
{
  error 1 "$@"
}


# dirlist_error EXIT_STATUS WHAT WHERE WHICH
# ------------------------------------------
# Report an error and exit with failure if WHICH, of type WHAT
# does not exist in WHERE.
# This function tests only directories
dirlist_error ()
{
  local err="$1"
  local type="$2"
  local base="$3"
  local val="$4"

  if test ! -d $base/$val; then
    stderr "no such $type $val, possible choices are :"
    for d in $base/*; do
      if test -d $d; then
	stderr "  - $(basename $d)"
      fi
    done
    exit $err
  fi
}

# exist_error EXIT_STATUS WHAT WHERE OPTION
# -----------------------------------------
# Report an error and exit with failure if WHERE is not found
# or is not of type WHAT.
# OPTION indicates which umake option to set for this value.
# This function tests only directories
exist_error ()
{
  local err="$1"
  local type="$2"
  local base="$3"
  local option="$4"
  local longtype="$2"

  case $type in
    d) longtype=directory;;
    f) longtype=file;;
  esac

  test "$type" = d -a -n "$base" &&
    base=$(dirname $base/.)

  if test ! -$type "$base"; then
    stderr "no such $longtype $base"
    if test -n "$option"; then
      stderr "  use option --$option to set to an alternative value."
    fi
    exit $err
  fi
}

# Initialize the common set up.  Should be done when $debug and
# $quiet are set.
initialize ()
{
  # File descriptor usage:
  # 0 standard input
  # 1 standard output (--verbose messages)
  # 2 standard error
  # 3 some systems may open it to /dev/tty
  # 4 used on the Kubota Titan
  # 5 tools output (turned off by --quiet)
  # 6 tracing/debugging (set -x output, etc.)

  # Main tools' output (TeX, etc.) that TeX users are used to seeing.
  #
  # If quiet, discard, else redirect to the error flow.
  if $quiet; then
    exec 5>/dev/null
  else
    exec 5>&2
  fi

  # Enable tracing, and auxiliary tools output.
  #
  # Should be used where you'd typically use /dev/null to throw output
  # away.  But sometimes it is convenient to see that output (e.g., from
  # a grep) to aid debugging.  Especially debugging at distance, via the
  # user.
  if $debug || test x"$VERBOSE" = xx; then
    exec 6>&1
    set -x
  else
    exec 6>/dev/null
  fi

  verbose "$0 running."
}

# append VARIABLE CONTENT [SEPARATOR=' ']
# ---------------------------------------
append ()
{
  local var="$1"
  local content="$2"
  local sep
  sep=${3-' '}
  eval "$var=\$$var\${$var:+$sep}\$content"
}

usage ()
{
    cat <<EOF
Usage: $me <install_dir>

General options:
  -h, --help           display this help and exit successfully
  -V, --version        display version information and exit successfully

Report bugs to sdk-remote-bugs@gostai.com.
EOF

  exit 0
}

version ()
{
  cat <<\EOF
uinstall UNDEFINED (Urbi SDK Remote UNDEFINED)
Copyright (C) 2004-2010, Gostai S.A.S.
EOF
  exit 0
}

installdir=

get_options ()
{
  # Push a token among the arguments that will be used to notice when we
  # ended options/arguments parsing.
  # Use "set dummy ...; shift" rather than 'set - ..." because on
  # Solaris set - turns off set -x (but keeps set -e).
  # Use ${1+"$@"} rather than "$@" because Digital Unix and Ultrix 4.3
  # still expand "$@" to a single argument (the empty string) rather
  # than nothing at all.
  arg_sep="$$--$$"
  set dummy ${1+"$@"} "$arg_sep"; shift

  # Parse command line arguments.
  while test x"$1" != x"$arg_sep"
  do
    # Handle --option=value by splitting apart and putting back on argv.
    case $1 in
      (--*=*)
	opt=`echo "$1" | sed -e 's/=.*//'`
	val=`echo "$1" | sed -e 's/[^=]*=//'`
	shift
	set dummy "$opt" "$val" ${1+"$@"}; shift
	;;
    esac

    case $1 in
      (-h | --help   ) usage;;
      (-V | --version) version;;

      (--) # What remains are not options.
	shift
	while test x"$1" != x"$arg_sep"
	do
	    set dummy ${1+"$@"} "$1"; shift
	    shift
	done
	break
	;;
      (-*)
	error 2 "Unknown or ambiguous option \`$1'." \
	      "Try \`--help' for more information."
	;;
      (*) set dummy ${1+"$@"} "$1"; shift;;
     esac
     shift
  done
  # Pop the token
  shift

  # Interpret remaining command line args as filenames.
  case $# in
   (0) error 2 "Missing install directory on command line.";;
   (1) installdir=$1;;
   (*) installdir=$1
       stderr "Extra unused arguments after install directory.";;
  esac
}

get_options "$@"
initialize

dir=$medir

# origin install dir
prefix='/prefix'
prefixdir="${prefix}"

# absolute current dir
currentdir="$dir/"
currentdir=$(cd $currentdir && pwd)
currentdir="${currentdir%/bin*}"

# Test install directory existency
if test ! -d "$installdir"; then
  mkdir -p "$installdir"
fi
installdir=$(cd $installdir && pwd)

# Test if install in sub directory of ourself to prevent cp loops
matchdir=$(echo "$installdir" | sed -ne "s#${currentdir}/##p")

if test -n "$matchdir"; then
  error 2 "Cannot install in a subdirectory of current directory."
fi

# Test for write permissions
install_test_file=$installdir/.urbi_install_test_file
touch -f $install_test_file 2>/dev/null || true
if test ! -f $install_test_file; then
  error 2 "Unable to create file in $installdir, you may need special permissions"
fi
rm -f $install_test_file 2>/dev/null

# Don't copy on ourself.
if test "$currentdir" != "$installdir"; then
  cp -pPR $currentdir/* $installdir/
  rm -f $installdir/bin/uinstall
fi

# Set paths to install directory
find $installdir							\
    -name \*.la -o -name umake\*					\
    -o -name uinstall -o -name \*.mk |					\
    xargs sed -i -e "/OPEN_R_SDK/! s#${prefixdir}#${installdir}#g"

# Special case for kernel includes.
find $installdir							\
    -name param.mk |							\
    xargs sed -i -e "s#^\(URBI_KERNEL_PATH = \).*#\1${installdir}#g"


exit 0

# Local variables:
# mode: shell-script
# End:
