#!/bin/sh
# (https://www.libsdl.org/)

parm="$1"
test "$parm" = "" && { echo "SDL2: parameter missing" >&2; exit 1; }

if test "$1" = "-h" || test "$1" = "--help"
then
  echo "(Un)Compiles libSDL2; called from Makefile"
  exit 1
fi

LIBVZ="libSDL2"
test "$MAKE" = "" && MAKE="make"

retw=0
if test "$parm" = "all"
then
  test -f config.status || { echo "SDL2: config.sh must be called before" >&2; exit 1; }
  DO_COMP=0
  grep "TAG=" config.status >/dev/null || DO_COMP=1

  test $DO_COMP -eq 0 && exit 0
  test -h $LIBVZ && exit 0

  test "$PREFIX" = "" && { echo "SDL2: PREFIX missing" >&2; exit 1; }

  tvz="SDL-release-2.*"
  tgzfile=`ls ${tvz}.tar.gz 2>/dev/null`
  if test "$tgzfile" = ""
  then
    tvz="SDL2-*"
    tgzfile=`ls ${tvz}.tar.gz 2>/dev/null`
    test "$tgzfile" = "" && exit 1
  fi

  tar pxzf "$tgzfile"
  sdlvz=""
  for vz in $tvz
  do
    test -d $vz && sdlvz=$vz
  done
  test "$sdlvz" = "" && exit 1
  rm -f $LIBVZ
  ln -s $sdlvz $LIBVZ

  cd $LIBVZ || exit 1

  test "$CC" = "cc" && unset CC
  unset CFLAGS
  unset MAKEFLAGS
  LDFLAGS="-L/usr/local/lib"
  export LDFLAGS
  ./configure --prefix=$PREFIX --disable-libudev
  test $? -eq 0 && $MAKE all install
  retw=$?

elif test "$parm" = "clean"
then
  rm -f config.status
  vz=""
  test -h $LIBVZ && vz=`readlink $LIBVZ`
  if test "$vz" != ""
  then
    rm -rf $vz
    rm -f $LIBVZ
  fi
fi

exit $retw
