#!/bin/sh
TARBALLDIR="/tmp"
FILENAME="GoogleEarthLinux.bin"
MD5SUM="737743e5ce9f464d555a2a829baebea4"
URL1="http://dl.google.com/earth/client/current/GoogleEarthLinux.bin"
URL2=""
do_installation() {
	set -e
	rm -rf /tmp/googleearth-pkg
	mkdir /tmp/googleearth-pkg
	cd /tmp/googleearth-pkg
	export DISPLAY=
	sh $TARBALLDIR/$FILENAME --target . --noexec
	tar -xf googleearth-linux-x86.tar -C /usr/lib/googleearth
	tar -xf googleearth-data.tar -C /usr/lib/googleearth
	# Does not exist as of 4.2.180.1134
	#cp -a EULA-GoogleEarth-en.html /usr/lib/googleearth
	chown -R root /usr/lib/googleearth
	chgrp -R root /usr/lib/googleearth
	convert googleearth-icon.png -resize 16x16 /usr/share/icons/mini/googleearth.png
	convert googleearth-icon.png -resize 32x32 /usr/share/icons/googleearth.png
	convert googleearth-icon.png -resize 48x48 /usr/share/icons/large/googleearth.png
	
	cat > /usr/bin/googleearth <<-FOE
	#!/bin/sh
	cd /usr/lib/googleearth
	export LD_LIBRARY_PATH=.:\$LD_LIBRARY_PATH
	exec "./googleearth-bin" "\$@"
	FOE
	chmod 0755 /usr/bin/googleearth
	cd /tmp
	rm -rf /tmp/googleearth-pkg
	rm -f /GoogleEarthLinux.bin
}

set -e

if [ ! -d "$TARBALLDIR" ]; then
	echo "Error: \"$TARBALLDIR\" does not exist." >&2
	exit 1
fi

if [ $(id -u) -ne 0 ]; then
	echo "Error: You must run this script as root." >&2
	exit 1
fi

LOCALFILE="$1"

if [ -n "$LOCALFILE" ]; then
	if [ ! -e "$LOCALFILE" ]; then
		echo "Error: Specified file \"$LOCALFILE\" does not exist." >&2
		exit 1
	fi
	if ! echo "$MD5SUM  $LOCALFILE" | md5sum -c &>/dev/null; then
		echo "Error: Specified file fails md5 hash check." >&2
		exit 1
	fi
		
	cp "$LOCALFILE" "$TARBALLDIR/$FILENAME"
	
else
	URLNUM=1
	FAILURE=false
	CONN_ERROR=false
        echo "Note that by downloading Google Earth you indicate your acceptance of"
        echo "the EULA, available from http://earth.google.com/download-earth.html"
	while ! echo "$MD5SUM  $TARBALLDIR/$FILENAME" | md5sum -c &>/dev/null; do
		eval URL="\$URL$URLNUM"
		if [ -z "$URL" ]; then
			FAILURE=true
			break
		fi
		URLNUM=$((URLNUM+1))
		echo "Downloading from $URL:"
		curl --connect-timeout 20 -m 10800 -L "$URL" > "$TARBALLDIR/$FILENAME"
	done
	if $FAILURE; then
		echo "Error: Unable to download Google Earth due to this package being too old." >&2
		echo "       You need to contact plf-discuss@zarb.org or" >&2
 		echo "       report a bug in the PLF bugzilla at http://plf.zarb.org/bugzilla/" >&2
		echo "       so that the package will be updated. Thank you." >&2
		exit 1
	fi
fi

do_installation

echo "Installation successful."
