#!/bin/sh

DIR=`dirname $0`
OPTION=$1

if test "$OPTION" != "-test" -a "`echo $UID`" != "0"; then
  echo "You must be root to use this program!"
  exit 0
fi

function readlink()
{
  ls -l $1|awk '{print $NF}'
}

pushd $DIR > /dev/null; BINDIR=`pwd`; popd > /dev/null

# only remove the symbolic links if they do not point to other OpenGL
# libraries, which do exist; switch to mesasoft if the package is 
# installed

if test "$OPTION" == "-removelinks"; then
( cd $DIR/../../lib
  if test `readlink libGL.so.1`; then
    if test `readlink libGL.so.1` == "GL/libGL.so.1.0.2960.nv_glx"; then 
      rm -f libGL.so.1 libMesaGL.so.3
      test -x $BINDIR/switch2mesasoft
      if [ $? -eq 0 ]; then
        $BINDIR/switch2mesasoft
        test -x $DIR/../../bin/chrc.config && \
          $DIR/../../bin/chrc.config SCRIPT_3D switch2mesasoft
      else
        test -x $DIR/../../bin/chrc.config && \
          $DIR/../../bin/chrc.config SCRIPT_3D no
      fi
    elif ! test -f `readlink libGL.so.1`; then
      rm -f libGL.so.1 libMesaGL.so.3
      test -x $BINDIR/switch2mesasoft
      if [ $? -eq 0 ]; then
        $BINDIR/switch2mesasoft
        test -x $DIR/../../bin/chrc.config && \
          $DIR/../../bin/chrc.config SCRIPT_3D switch2mesasoft
      else
        test -x $DIR/../../bin/chrc.config && \
          $DIR/../../bin/chrc.config SCRIPT_3D no
      fi
    fi
  fi
  if test `readlink libGLcore.so.1`; then
    if test `readlink libGLcore.so.1` == "libGLcore.so.1.0.2960.nv_glx"; then
      rm -f libGLcore.so.1
    else
      test -f `readlink libGLcore.so.1` || rm -f libGLcore.so.1
    fi
  fi
)
( cd $DIR/../lib/modules/extensions
  if test `readlink libglx.so`; then
    if test `readlink libglx.so` == "libglx.so.1.0.2960.nv_glx"; then
      rm -f libglx.so
    else
      test -f `readlink libglx.so` || rm -f libglx.so
    fi
  fi
)

elif test "$OPTION" == "-test"; then
pushd $DIR/../../lib > /dev/null
  test -L libGL.so.1 || exit 1
  test `readlink libGL.so.1` || exit 1
  test `readlink libGL.so.1` == "GL/libGL.so.1.0.2960.nv_glx" || exit 1
  test -L libGLcore.so.1 || exit 1
  test `readlink libGLcore.so.1` || exit 1
  test `readlink libGLcore.so.1` == "libGLcore.so.1.0.2960.nv_glx" || exit 1
popd > /dev/null
pushd $DIR/../lib/modules/extensions > /dev/null
  test -L libglx.so || exit 1
  test `readlink libglx.so` || exit 1
  test `readlink libglx.so` == "libglx.so.1.0.2960.nv_glx" || exit 1
  test -e libglx.a && exit 1
  test -e libGLcore.a && exit 1
popd > /dev/null
exit 0

else
( cd $DIR/../../lib
  ln -sf GL/libGL.so.1.0.2960.nv_glx libGL.so.1
  ln -sf libGL.so.1 libMesaGL.so.3
  ln -sf libGLcore.so.1.0.2960.nv_glx libGLcore.so.1
)
( cd $DIR/../lib/modules/extensions
  ln -sf libglx.so.1.0.2960.nv_glx libglx.so
  rm -f libglx.a libGLcore.a
)
test -x $DIR/../../bin/chrc.config && \
  $DIR/../../bin/chrc.config SCRIPT_3D switch2nvidia_glx
fi
