#!/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 '*.wav' --exclude '*' ../data/sounds "$TARGET/bin"

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

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

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

mkdir -p "$TARGET/bin/locale/cs/LC_MESSAGES"
cp ../build/data/translations/cs.gmo "$TARGET/bin/locale/cs/LC_MESSAGES/dxirc.mo"

mkdir -p "$TARGET/bin/locale/sk/LC_MESSAGES"
cp ../build/data/translations/sk.gmo "$TARGET/bin/locale/sk/LC_MESSAGES/dxirc.mo"

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

mkdir -p "$TARGET/lib"
rsync -a -m --include '*/' --include '*.dll' --include '*.cache' --exclude '*' /mingw32/lib/enchant-2 "$TARGET/lib"

mkdir -p "$TARGET/share/enchant"
rsync -a -m --include '*/' --include '*.aff' --include '*.dic' --include '*.txt' --exclude '*' /mingw32/share/enchant/hunspell "$TARGET/share/enchant"

DLLSOURCE=/mingw32/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
}

pacman -Ql mingw-w64-i686-openssl | grep '\.dll' | while read dll
do
  path=${dll#* }
  copydll "$path"
done

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