#!/bin/bash

SERVIIO_HOME=/usr/local/serviio
SERVIIO_LIBRARY=$SERVIIO_HOME/library
export SERVIIO_LIB=$SERVIIO_HOME/lib

#get the full path
CWD=`(\cd ${0%/*} && /bin/pwd) 2>/dev/null`
DERBY_IJ="$CWD/ij"

# For derby.log
\cd ${TMPDIR:=/tmp}

SERVIIO_TABLES=`(cat << !EOS | $DERBY_IJ 2>/dev/null | /bin/sed -e '/^[ \t]*APP/!d' -e 's/^[ \t]*APP[ \t]*|\(.*\)[ \t]*|.*/\1/1' | /usr/bin/xargs
  connect 'jdbc:derby:$SERVIIO_LIBRARY/db';
  show tables in APP;
  disconnect;
  quit;
!EOS
)2>/dev/null`

if [ -z "$SERVIIO_TABLES" ]; then
  echo "No Serviio tables found!!!, check $SERVIIO_LIBRARY. Exiting"
  exit 1
fi
echo "Serviio tables to be compressed: $SERVIIO_TABLES"

TEMPFILE=`/bin/mktemp $TMPDIR/sql.XXXXXXXXXX 2>/dev/null || exit 2`

cat << !EOS > $TEMPFILE
  connect 'jdbc:derby:$SERVIIO_LIBRARY/db';
!EOS

for table in $SERVIIO_TABLES; do
  cat << !EOS >> $TEMPFILE
    call SYSCS_UTIL.SYSCS_COMPRESS_TABLE('APP', '$table', 0);
!EOS
done

cat << !EOS >> $TEMPFILE
    disconnect;
    quit;
!EOS

$DERBY_IJ $TEMPFILE 2>/dev/null

/bin/rm -f $TEMPFILE
exit 0;
