#!/bin/bash

# Build Drawpile server stable branch AppImage
# Run inside a CentOS 6 docker image.
# This script is partially based on https://github.com/probonopd/AppImages/blob/master/recipes/subsurface/Recipe

set -e
set -x

. /opt/rh/devtoolset-3/enable

SRCDIR=/Drawpile
WORKDIR=/work
BUILDDIR=/build
APPDIR=/Drawpile.AppDir
APPIMGKIT=/AppImageKit-master

# Build server
mkdir -p $BUILDDIR
mkdir -p $APPDIR
cd $BUILDDIR
cmake3 $SRCDIR -DSERVER=ON -DCLIENT=OFF -DSERVERGUI=OFF -DINSTALL_DOC=OFF -DCMAKE_INSTALL_PREFIX=$APPDIR/usr
make -j5

# Install only the required server parts
mkdir -p $APPDIR/usr/bin
cp bin/drawpile-srv $APPDIR/usr/bin
mkdir -p $APPDIR/usr/share/drawpile-srv

# Construct AppDir bundle
cd $APPDIR

cp $APPIMGKIT/AppRun .
chmod a+x AppRun


# Copy libraries
mkdir -p usr/lib/qt5/plugins
cd usr
ln -s lib lib64
cd ..
cp -r /usr/lib64/qt5/plugins/sqldrivers usr/lib/qt5/plugins

ldd usr/bin/drawpile-srv | grep "=>" | awk '{print $3}' | xargs -I '{}' cp -vL '{}' ./usr/lib/ || true

cd usr/ ; find . -type f -exec sed -i -e 's|/usr/lib|././/lib|g' {} \; ; cd ..

# Remove blacklisted libs
BLACKLISTED_FILES=$(sed '/^\s*$/d' $SRCDIR/pkg/appimage/excludelist | sed '/^#.*$/d')
for FILE in $BLACKLISTED_FILES ; do
	FOUND=$(find . -type f -name "${FILE}" 2>/dev/null)
	if [ ! -z "$FOUND" ] ; then
		echo "Deleting blacklisted ${FOUND}"
		rm -f "${FOUND}"
	fi
done


# Copy desktop stuff
cat <<END > drawpile-srv.desktop
[Desktop Entry]
Version=1.0
Name=Drawpile Server

GenericName=Dedicated server for Drawpile

Exec=drawpile-srv
Type=Application
Icon=drawpile
Categories=Network;
Terminal=true

END

cp $SRCDIR/desktop/drawpile-48x48.png $APPDIR/drawpile.png

# Build Appimage

cd /Drawpile
VERSION=$(ls $APPDIR/usr/bin/drawpile-* | cut -d - -f 2-)
APPIMAGE="Drawpile-$VERSION.AppImage"

rm -f /out/$APPIMAGE
$APPIMGKIT/AppImageAssistant.AppDir/package $APPDIR /out/$APPIMAGE

