#!/bin/bash
if [ -z "$1" ]; then
    echo "Syntax: $0 <targetdir>" 1>&2
    exit 1
fi

TARGET=$1

mkdir -p "$TARGET"

rm -rfv "$TARGET"/*

mkdir -p "$TARGET/bin"

cp ../COPYING "$TARGET/bin"

rsync -a -m --include '*/' --include '*.pem' --exclude '*' ${MINGW_PREFIX}/bin/ca-certs "$TARGET/bin"

rsync -a -m --include '*/' --include '*.wav' --exclude '*' ../data/sounds "$TARGET/bin"

rsync -a -m --include '*/' --include '*.png' --include '*.csv' --exclude '*' ../data/icons "$TARGET/bin"

rsync -a -m --include '*/' --include 'qt*cs.qm' --exclude '*' ${MINGW_PREFIX}/share/qt5/translations "$TARGET/bin"

rsync -a -m --include '*/' --include 'qwin*.dll' --exclude '*' ${MINGW_PREFIX}/share/qt5/plugins/platforms "$TARGET/bin"

mkdir -p "$TARGET/bin/locale/cs"
rsync -a -m --include '*/' --include 'pidgin*' --exclude '*' ${MINGW_PREFIX}/share/locale/cs/LC_MESSAGES "$TARGET/bin/locale/cs"

cp ../build/data/translations/cs.gmo "$TARGET/bin/locale/cs/LC_MESSAGES/dxim.mo"

installapp ../build/fox "$TARGET/bin"
installapp ../build/qt "$TARGET/bin"
installapp ../build/gtkmm "$TARGET/bin"

mkdir -p "$TARGET/share/locale/cs"
rsync -a -m --include '*/' --include 'atk*' --include 'gdk*' --include 'glib*' --include 'gtk3*' --exclude '*' ${MINGW_PREFIX}/share/locale/cs/LC_MESSAGES "$TARGET/share/locale/cs"

DLLSOURCE=${MINGW_PREFIX}/bin/
copydll() {
  b="$(basename $1)"
  echo "Copy dll for '$b'"
  strings "$1" | grep '\.dll' | while read dll
  do
    DLL=`find "$DLLSOURCE" -maxdepth 1 -name "$dll" -print -quit`
    if [ ! -z "$DLL" ]; then
      FILE="$TARGET/bin/$(basename $DLL)"
      if [ ! -f "$FILE" ]; then
         cp -a "$DLL" "$TARGET/bin/"
         copydll "$DLL"
      fi
    fi
  done
}

cp "../build/purplemm/src/libpurplemm.dll" "$TARGET/bin"
copydll "../build/purplemm/src/libpurplemm.dll"

pacman -Ql ${MINGW_PACKAGE_PREFIX}-pidgin | grep '\.dll$' | while read dll
do
  path=${dll#* }
  copydll "$path"
done

mkdir -p "$TARGET/lib/purple-2"
find ${MINGW_PREFIX}/lib/purple-2/ -type f -name '*.dll' -exec cp {} "$TARGET/lib/purple-2" \;

pacman -Ql ${MINGW_PACKAGE_PREFIX}-purple-icyque-git | grep '\.dll$' | while read dll
do
  path=${dll#* }
  copydll "$path"
done

pacman -Ql ${MINGW_PACKAGE_PREFIX}-purple-slack-git | grep '\.dll$' | while read dll
do
  path=${dll#* }
  copydll "$path"
done

#find "$TARGET/bin/sasl2" -name "*.dll" -print0 | while IFS= read -r -d '' file; do copydll "$file"; done
