#!/bin/bash
#
ARCH=`uname -m`

LIB="../lib/linux-$ARCH"
BUILD="../build/Release"

mkdir -p $LIB
rm -f $LIB/*.so*
cp $BUILD/*.so $LIB
cp $BUILD/rktwebview_prg $LIB

QT_PATH=`ldd $BUILD/rktwebview_prg | grep Qt | awk '{print $3}' | head -1 | sed -e 's%[/]lib[/].*%%'`
echo "QT_PATH=$QT_PATH"

QT_PLUGINS="$QT_PATH/plugins"
PLUGINS="platforms position generic iconengines imageformats qmltooling tls xcbglintegrations"

EXTRA_LIBS_SO=`ldd $BUILD/rktwebview_prg | grep Qt | awk '{ print $3 }'`
EXTRA_LIBS_PLATFORM_PLUGIN_XCB=`ldd $QT_PATH/plugins/platforms/libqxcb.so | grep Qt | awk '{print $3}'`

for pl in $PLUGINS
do
  echo "Assembling libs for $pl"
  LIBS=`ls $QT_PLUGINS/$pl | grep so`
  for ll in $LIBS
  do
    l="$QT_PLUGINS/$pl/$ll"
    ELS=`ldd $l | grep Qt | grep -v no\ version\ information | awk '{print $3}'`
    EXTRA_LIBS_SO="$EXTRA_LIBS_SO $ELS"
  done
done

#echo $EXTRA_LIBS_SO | less

EXTRA_LIBS=`echo $EXTRA_LIBS_SO $EXTRA_LIBS_PLATFORM_PLUGIN_XCB | sort | uniq`

for l in $EXTRA_LIBS; do 
  version_so=`basename $l`
  if [ ! -r "$LIB/$version_so" ]; then
     echo "Copying $l..." 
     cp $l $LIB
     so=`echo $version_so | sed -e 's/[.]so.*$//'`
     lib_so=`echo -n $so; echo ".so"`
     (cd $LIB; ln -s $version_so $lib_so)
  fi
done


for p in $PLUGINS
do
   echo "Plugin $p..."
   (cd $QT_PLUGINS; tar cf - $p) | (cd $LIB; tar xf -)
done

RESOURCES="resources translations"
QT_RESOURCES="$QT_PATH"

for r in $RESOURCES
do
   echo "Resource $r..."
   (cd $QT_RESOURCES; tar cf - $r) | (cd $LIB; tar xf - )
done

cp $QT_PATH/libexec/QtWebEngineProcess $LIB

(cd $LIB; cd ..; zip -9 -y -r linux-$ARCH.zip linux-$ARCH)




