#! /bin/bash


#qt_com=$(arch)
qt_com=`arch`
if [ $qt_com = "aarch64" ];then
Qtgccdir='/usr/lib/aarch64-linux-gnu/qt5'
QtPlatformdir=$Qtgccdir/plugins/platforms
QtLibDir=/usr/lib/aarch64-linux-gnu/
else
Qtgccdir='/opt/Qt5.10.1/5.10.1/gcc_64'
QtPlatformdir=$Qtgccdir/plugins/platforms
QtLibDir=$Qtgccdir/lib
fi


ignore_lib_name=(
libstdc++.so.*
libm.so.*
libgcc_s.so.*
libc.so.*
libpthread.so.*
libGL.so.*
libz.so.*
libgthread*
libglib*
libexpat*
libxcb*
libdl.so.*
libxshmfence*
libglapi.so.*
libXext.so.*
libXdamage.so.*
libXfixes.so.*
libX11*
libXxf86vm.so.*
libdrm.so.*
libpcre.so.*
libXau.so.*
libXdmcp.so.*
)

EXE="$1"
PWD=`pwd`
rm -rf app
mkdir app
cd app
mkdir lib
cd ..
mkdir commonlib
cd commonlib
mkdir platforms
cp $QtPlatformdir/libqxcb.so platforms
cd platforms
mkdir lib
libfiles=`ldd libqxcb.so | awk '{ if(match($3,"^/"))printf("%s "),$3 }'` 
cp $libfiles $PWD/lib 
cd ..
mkdir lib
cp $QtLibDir/libQt5DBus.* $PWD/lib
cp $QtLibDir/libQt5XcbQpa.* $PWD/lib
rm -rf $PWD/platforms/lib
cd platforms

cd ..
cd ..

files=`ldd $EXE | awk '{ if(match($3,"^/"))printf("%s "),$3 }'`
cp $files $PWD/app/lib
cp $PWD/commonlib/lib/* $PWD/app/lib
cp -r  $PWD/commonlib/platforms $PWD/app
cp $EXE $PWD/app

for x in ${ignore_lib_name[@]}
do
rm -f $PWD/app/lib/${x}
done

rm -rf commonlib

cd app
patchelf --set-rpath '$ORIGIN/lib/' $EXE
if [ "$?" != 0 ];then
	echo -e "\e[31m deploy.sh: patchelf $EXE faile, Ensure patchelf tool installed\e[0m"
	exit 1
fi
cd platforms
patchelf --set-rpath '$ORIGIN/../lib/' libqxcb.so
if [ "$?" != 0 ];then
	echo -e "\e[31m deploy.sh: patchelf $EXE faile, Ensure patchelf tool installed\e[0m"
#	exit 1
fi
cd ..
cd ..

cp -r app $PWD/deploy/

rm -rf app