#!/bin/sh
# (https://xiph.org/downloads/)

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

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

LIBOGGVZ="libogg"
LIBVORBISVZ="libvorbis"
test "$MAKE" = "" && MAKE="make"

retw=0
if test "$parm" = "all"
then
  test -h $LIBVORBISVZ && exit 0

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

  unset CFLAGS
  unset MAKEFLAGS
  CFLAGS="-I$PREFIX/include"
  export CFLAGS
  LDFLAGS="-L/usr/local/lib -L$PREFIX/lib"
  export LDFLAGS

  # libogg
  tgzfile=`ls libogg-*.tar.gz`
  test "$tgzfile" = "" && exit 1
  tar pxzf "$tgzfile"
  wrkvz=""
  for vz in libogg-*
  do
    test -d $vz && wrkvz=$vz
  done
  test "$wrkvz" = "" && exit 1
  rm -f $LIBOGGVZ
  ln -s $wrkvz $LIBOGGVZ
  cd $LIBOGGVZ || exit 1
  ./configure --prefix=$PREFIX --disable-shared
  test $? -eq 0 && $MAKE all install
  retw=$?
  test $retw -ne 0 && exit $retw
  cd ..

  # libvorbis
  tgzfile=`ls libvorbis-*.tar.gz`
  test "$tgzfile" = "" && exit 1
  tar pxzf "$tgzfile"
  wrkvz=""
  for vz in libvorbis-*
  do
    test -d $vz && wrkvz=$vz
  done
  test "$wrkvz" = "" && exit 1
  rm -f $LIBVORBISVZ
  ln -s $wrkvz $LIBVORBISVZ
  cd $LIBVORBISVZ || exit 1
  ./configure --prefix=$PREFIX --disable-shared --disable-oggtest
  test $? -eq 0 && $MAKE all install
  retw=$?
  test $retw -ne 0 && exit $retw
  cd ..

  # vgag-ogg
  $CC -W -Wall -O2 -I$PREFIX/include -L$PREFIX/lib vgag-ogg.c -lvorbisfile -lvorbis -logg -lm -o $PREFIX/bin/vgag-ogg
  cd ..

elif test "$parm" = "clean"
then
  # libogg
  vz=""
  test -h $LIBOGGVZ && vz=`readlink $LIBOGGVZ`
  if test "$vz" != ""
  then
    rm -rf $vz
    rm -f $LIBOGGVZ
  fi

  # libvorbis
  vz=""
  test -h $LIBVORBISVZ && vz=`readlink $LIBVORBISVZ`
  if test "$vz" != ""
  then
    rm -rf $vz
    rm -f $LIBVORBISVZ
  fi
fi

exit $retw
