#!/bin/bash -x

set +e

# Generate AppImage using the binaries currently provided by the project.
# These require at least GLIBC 2.14, which older distributions might not have. 
# On the other hand, 2.14 is not that recent so maybe we can just live with it.

APP=QGroundControl

mkdir -p $APP/$APP.AppDir
cd $APP/

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

wget -c "http://qgroundcontrol.s3.amazonaws.com/master/qgroundcontrol.tar.bz2"
tar xf ./qgroundcontrol.tar.bz2
wget -c http://ftp.us.debian.org/debian/pool/main/u/udev/udev_175-7.2_amd64.deb
wget -c http://ftp.us.debian.org/debian/pool/main/e/espeak/espeak_1.46.02-2_amd64.deb
wget -c http://ftp.us.debian.org/debian/pool/main/libs/libsdl1.2/libsdl1.2debian_1.2.15-5_amd64.deb

cd $APP.AppDir/

mv ../qgroundcontrol/* .
mv qgroundcontrol-start.sh AppRun
find ../ -name *.deb -exec dpkg -x {} . \;

# Workaround until 
# https://github.com/mavlink/qgroundcontrol/pull/3129
# is merged
cat > ./AppRun <<\EOF
#!/bin/sh
HERE="$(dirname "$(readlink -f "${0}")")"
export LD_LIBRARY_PATH="${HERE}/usr/lib/x86_64-linux-gnu":"${HERE}/usr/lib/":"${HERE}/Qt/libs":$LD_LIBRARY_PATH
export QML2_IMPORT_PATH="${HERE}/Qt/qml"
export QT_PLUGIN_PATH="${HERE}/Qt/plugins"
"${HERE}/qgroundcontrol" "$@"
EOF

# Get icon
wget "https://raw.githubusercontent.com/mavlink/qgroundcontrol/948b89753aa0b60f29f46ea0918feae05084d178/resources/icons/qgroundcontrol.png"

cat > ./qgroundcontrol.desktop <<\EOF
[Desktop Entry]
Type=Application
Name=QGroundControl
GenericName=Ground Control Station
Comment=UAS ground control station
Icon=qgroundcontrol
Exec=AppRun
Terminal=false
Categories=Utility;
Keywords=computer;
EOF

get_desktopintegration qgroundcontrol

VERSION=$(strings qgroundcontrol | grep v[0-9*]\.[0-9*]\.[0-9*]-[0-9*] | head -n 1)

# Go out of AppImage
cd ..

generate_appimage
