#!/bin/bash
#
BASEURL="http://spike.economicoutlook.net"
INSTALLBASE=/opt
VIEWERBASE=SpikeViewer
ABSSCRIPTNAME="$(cd "${0%/*}" 2>/dev/null; echo "$PWD"/"${0##*/}")"

msg() {
echo -e "$@"
echo -en "\n(press return to continue)"
read
}

echo
case $(uname -m) in *x86_64*) ARCH=linux.gtk.x86_64 ;; *)ARCH=linux.gtk.x86 ;; esac
rm -rf /var/tmp/$ARCH* || { msg "sudo ?" ; exit 1; }
rm -rf $INSTALLBASE/$VIEWERBASE || { msg "sudo ?" ; exit 1; }
cd /var/tmp || { msg "can't access /var/tmp/\!" ; exit 1; }
[ -x "$(which curl 2>/dev/null)" ] && {
	curl -o $ARCH.tar.bz2 $BASEURL/$ARCH.tar.bz2 || { msg "curl download failed\!" ; exit 1; }
} || {
	wget -O $ARCH.tar.bz2 $BASEURL/$ARCH.tar.bz2 || { msg "wget download failed\!" ; exit 1; }
}
tar -xjf $ARCH.tar.bz2 || { msg "extract failed\!" ; exit 1; }
mv $ARCH/$VIEWERBASE  $INSTALLBASE || { msg "install failed\!" ; exit 1; }
chown root:root $INSTALLBASE/$VIEWERBASE -R
find $INSTALLBASE/$VIEWERBASE -type d -exec chmod 755 {} +
find $INSTALLBASE/$VIEWERBASE -type f -exec chmod 444 {} +
chmod +x $INSTALLBASE/$VIEWERBASE/SpikeViewer

rm -f /usr/local/bin/spike
cat >/usr/local/bin/spike <<-EOF
	#!/bin/sh
	# export GDK_NATIVE_WINDOWS=1
	export UBUNTU_MENUPROXY=0
	exec  /opt/SpikeViewer/SpikeViewer
EOF
chmod 555 /usr/local/bin/spike

cat >/usr/share/applications/spike.desktop <<-EOF
		[Desktop Entry]
		Version=1.0
		Encoding=UTF-8
		Name=Spike Viewer
		Type=Application
		Comment=Spike Viewer
		Categories=GNOME;Application;Office;
		Terminal=false
		Exec=/usr/local/bin/spike
		Icon=/opt/SpikeViewer/icon.xpm
EOF

[ "$ABSSCRIPTNAME" = /usr/local/bin/install_spikeviewer_gnome ] || cat $ABSSCRIPTNAME >/usr/local/bin/install_spikeviewer_gnome
chmod 555 /usr/local/bin/install_spikeviewer_gnome

cat >/usr/share/applications/spike_update.desktop <<-EOF
		[Desktop Entry]
		Version=1.0
		Encoding=UTF-8
		Name=Spike Updater
		Type=Application
		Comment=Spike Updater
		Categories=GNOME;Application;Office;
		Terminal=true
		Exec=sudo /usr/local/bin/install_spikeviewer_gnome
		Icon=/opt/SpikeViewer/icon.xpm
EOF

msg "Spike updater finished."
