#!/bin/bash -x

set +e

APP=LibreOffice
VERSION=$(wget -q "http://www.libreoffice.org/download/libreoffice-fresh/" -O - | grep -o -e "/dl/src/.*/all/" | cut -d "/" -f 4 | head -n 1)
OOODOWNLOADLINK="http://download.documentfoundation.org/libreoffice/stable/"$VERSION"/deb/x86_64/LibreOffice_"$VERSION"_Linux_x86-64_deb.tar.gz"
# VERSION="5.2.0.3"
# OOODOWNLOADLINK="http://download.documentfoundation.org/libreoffice/testing/5.2.0/deb/x86_64/LibreOffice_5.2.0.3_Linux_x86-64_deb.tar.gz"
mkdir -p ./$APP/$APP.AppDir
cd ./$APP

wget -q https://github.com/probonopd/AppImages/raw/master/functions.sh -O ./functions.sh

# OpenOffice 5.3 is too large to fit into the 250 MB limit using gzip squashfs compression
sed -i -e 's|VERSION ./appimagetool|VERSION ./appimagetool --comp xz|g' ./functions.sh

. ./functions.sh

wget -c "$OOODOWNLOADLINK"

tar xfvz *.tar.gz

rm -f LibreOffice_*/DEBS/*extension-javascript-script-provider_*.deb LibreOffice_*/DEBS/*onlineupdate_*.deb LibreOffice_*/DEBS/*extension-mediawiki-publisher_*.deb LibreOffice_*/DEBS/*dict-es*.deb || true # Need to get under 250 MB for Bintray

cd $APP.AppDir/

find ../ -name *.deb -exec dpkg -x \{\} . \;

find . -name startcenter.desktop -exec cp \{\} . \;

# No, dear LibreOffice developers, "Name=LibreOffice 5.2"
# is not a good .desktop file entry. There should be a SoftwareVersion=
# entry in the Desktop Entry Specification, but there isn't
sed -i -e 's|Name=.*|Name=LibreOffice|g' startcenter.desktop

find -name *startcenter.png -path *hicolor*48x48* -exec cp \{\} . \;

BINARY=$(cat *.desktop | grep "Exec=" | head -n 1 | cut -d "=" -f 2 | cut -d " " -f 1)

mkdir -p usr/bin/
cd usr/bin/
rm ./$BINARY
find ../../opt -name soffice -path *program* -exec ln -s \{\} ./$BINARY \;
cd ../../

get_apprun

# The following is a real dirty hack to stay under the Bintray 250 MB file size limit 
# We are deleting some of the largest Python binary libraries
# Hopefully no Python macros are crashing because of this
# TODO: Find something else to strip away or get better compression or get Bintray
# to lift the filesize limit
find . -name _ssl.cpython* -exec rm {} \; || true
find . -name _decimal.cpython* -exec rm {} \; || true
find . -name _hashlib.cpython* -exec rm {} \; || true

cd ..

generate_type2_appimage
