#! /bin/bash

Qtgccdir= '' #'/usr/lib/x86_64-linux-gnu/qt5'
if [ ${#Qtgccdir} -lt 6 ]; then
  echo "Because not set gcc_64 , so auto find gcc_64 "
  optfiles=`find /opt -name 'gcc_64'` 
  for entry in $optfiles
  do
     if [ ${entry:0-6:6} == "gcc_64" ];  then
       if [ -d $entry ];  then
          Qtgccdir="$entry"
	  echo -e "\033[32m""  -----found gccdir:"$Qtgccdir"\033[0m"
       fi
     fi
  done
fi

if [ ${#Qtgccdir} -lt 6 ]; then
  if [ -d '/usr/lib/aarch64-linux-gnu/qt5' ]; then
    Qtgccdir='/usr/lib/aarch64-linux-gnu/qt5'
  else 
    echo "if NVIDIA,please sudo apt install qt"
  fi
fi

if [ ${#Qtgccdir} -lt 6 ]; then
  if [ -d '/usr/lib/x86_64-linux-gnu/qt5' ]; then
    echo " Qt in /usr/lib"
    Qtgccdir='/usr/lib/x86_64-linux-gnu/qt5'
    QtPlatformdir=$Qtgccdir/plugins/platforms
    QtLibDir=/usr/lib/x86_64-linux-gnu/
  else 
    echo "please sudo apt install qt"
  fi
fi

if [ ${#Qtgccdir} -lt 6 ]; then
   echo -e "\033[31m""  -----not found gccdir: so exit""\033[0m"
   exit 1
fi


ignore_lib_name=(
libstdc++.so.*
libm.so.*
libgcc_s.so.*
#libc.so.*
#libpthread.so.*
#libGL.so.*
libz.so.*
libc.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/

xlib=`ls ./deploy/app/lib/lib*`  
for fileName in $xlib
  do
     patchelf --set-rpath '$ORIGIN' $fileName
  done

rm -rf app