#!/bin/bash
FAILS=""
MAINEXPORTDIR="/export"
TESTUSRLIB="/kindle/usr/lib/"
TESTLIB="/kindle/lib/"

# fail on missing victim
if [ -z ${@} ]
then
  echo "hmm I need a victim... usage: filechecker <binary_file>"
exit 1
fi
# fail on missing victim
if [ ! -e ${@} ]
then
  echo "hmm I cannot find: ${@} - you sure? check the file exists."
exit 1
fi

BINARY=$(basename ${@})
EXPORTDIR="${MAINEXPORTDIR}""/""${BINARY}"
mkdir -p $EXPORTDIR/bin
mkdir -p $EXPORTDIR/lib
mkdir -p $EXPORTDIR/kindle-lib
cd $EXPORTDIR

# copy the binary we are interested in
cp -f ${@} "${EXPORTDIR}/bin/${BINARY}"
echo "copying ${@} to ${EXPORTDIR}/bin/${BINARY}"

echo "finding all dependencies and copying them to $EXPORTDIR/lib"
echo "this will take a couple seconds, please wait..."
ldd ${@} | grep "=> /" | awk '{print $3}' | xargs -I '{}' cp -v '{}' $EXPORTDIR/lib > /dev/null

echo "Done. Now going to see if any of these libraries are already on the Kindle Touch (5.3.7)..."
find $EXPORTDIR/lib -type f | while read filename
  filename=$( basename $filename 2>/dev/null) 
do
echo
echo "checking $EXPORTDIR/lib/$filename.."
  if [ -f $TESTUSRLIB$filename ]; then
    if cmp --quiet $TESTUSRLIB$filename $EXPORTDIR/lib/$filename; then
      echo "$EXPORTDIR/lib/$filename is the same as my Kindle version - deleting!"
      rm $EXPORTDIR/lib/$filename
    fi
    echo "* Kindle /usr/lib support: moving $filename to $EXPORTDIR/kindle-lib/"
    mv $EXPORTDIR/lib/$filename $EXPORTDIR/kindle-lib/
  fi
  if [ -f $TESTLIB$filename ]; then
    if cmp --quiet $TESTUSRLIB$filename $EXPORTDIR/lib/$filename; then
      echo "$EXPORTDIR/lib/$filename is the same as my Kindle version - deleting"
      rm $EXPORTDIR/lib/$filename
    fi
    echo "* Kindle /lib support: moving $filename to $EXPORTDIR/kindle-lib/"
    mv $EXPORTDIR/lib/$filename $EXPORTDIR/kindle-lib/
  fi
done

#no need to have this at all ??
if [ -f $EXPORTDIR/kindle-lib/libc.so.6 ]; then
  echo
  echo "*** removing unneeded libc.so.6.." 
  rm $EXPORTDIR/kindle-lib/libc.so.6
fi

#remove empty lib dir
if [[ "$(ls -1 $EXPORTDIR/lib | wc -l)" == "0" ]] ; then
  rmdir $EXPORTDIR/lib
else
  echo
  echo "$EXPORTDIR/lib has: `ls -1 $EXPORTDIR/lib | wc -l` files:"
  ls -1 $EXPORTDIR/lib
  echo
fi

touch $EXPORTDIR/README
echo "Directories created in $EXPORTDIR. kindle-lib has newer versions of Kindle libraries." | tee $EXPORTDIR/README
echo "These are normally not needed. Run the program like this:" | tee $EXPORTDIR/README
echo "cd $EXPORTDIR/bin; LD_LIBRARY_PATH=../lib:\$LD_LIBRARY_PATH ./$BINARY" | tee $EXPORTDIR/README
