################################################################################################
# The Google Earth license does not allow to redistribute it, but you can generate
# your own Google Earth AppImage by running this script on a x86_64 Linux system:
#
# wget https://raw.githubusercontent.com/probonopd/AppImages/master/recipes/googleearth/Recipe
# bash -ex Recipe
################################################################################################

APP=GoogleEarth
LOWERAPP=${APP,,}

set -e

mkdir -p ./$APP/$APP.AppDir/usr/lib

cd ./$APP/

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

wget -c https://dl.google.com/dl/earth/client/current/google-earth-stable_current_amd64.deb

# Compile patchelf
if [ ! -f ./patchelf-0.9/src/patchelf ] ; then
  wget https://nixos.org/releases/patchelf/patchelf-0.9/patchelf-0.9.tar.bz2
  tar xf patchelf-0.9.tar.bz2
  ( cd patchelf-0.9/ && ./configure  && make )
fi

cd ./$APP.AppDir/
find ../*.deb -exec ar p {} data.tar.xz \; | tar xJ || true

# Change the interpreter; Google Earth uses an unusual one that is
# installed on almost no system out-of-the-box
../patchelf-0.9/src/patchelf --set-interpreter /lib64/ld-linux-x86-64.so.2 opt/google/earth/free/googleearth-bin

# Set the rpath so that libraries in the same directory as the executable
# are also found. Note that we also need to do this on libraries that load
# other libraries.
find opt/google/earth/ -type f -executable -exec ../patchelf-0.9/src/patchelf --set-rpath \$ORIGIN {} \;

# Clean up the directory structure
rm -rf etc usr
mkdir -p usr
mv opt/google/earth/free usr/bin

# Nice script @icculus but no longer needed
( cd usr/bin ; mv -f googleearth-bin google-earth )

cp ./usr/bin/product_logo_128.png google-earth.png
cp ./usr/bin/google-earth.desktop .
sed -i -e 's|^Exec=.*|Exec=google-earth|g' google-earth.desktop

get_desktopintegration google-earth

# Fix .desktop file so that it passes validation
sed -i -e 's|MultipleArgs|X-MultipleArgs|g' google-earth.desktop

ln -s ./usr/bin/google-earth.wrapper AppRun

rm -rf ./opt/

VERSION=$(strings ./usr/bin/libgoogleearth_free.so | grep SetupVersionInfo -C 1 | head -n 3 | tail -n 1)

cd .. # Get out of the AppImage

generate_appimage
