#!/bin/dash
# download latest google-talk plugin
# original by jamesbond 2015 for firefox-updater
# adulterated by kirk and re-hacked by james
# MIT license
# internationalized by L18L

export TEXTDOMAIN=get_app

### config
APPTITLE="$(gettext 'Download Google Talk plugin')"
PKGNAME=gtalk-plugin
WORKDIR=/tmp/work/update-google-talk.$$

### generic helpers
get_config() {
	if [ $(id -u) -ne 0 ]; then
		msg "$(gettext 'You must be root.')"
		exit 1
	fi
	LATEST=$(date +%Y.%m.%d) # can't determine version
	LIBDIR=lib64
	ARCH=amd64 # or i386 for 32-bit
	DOWNLOAD_PATH=http://dl.google.com/linux/direct/google-talkplugin_current_$ARCH.deb
}

# $1-text
msg() {
	[ -z "$DISPLAY" ] && echo "$1" ||
	Xdialog --title "$APPTITLE" --infobox "$1" 0 0 10000
}

# $1-text, returns true/false
yesno() {
	local p
	if [ -z "$DISPLAY" ]; then
		printf "%s\nType [yes] to continue: " "$1"
		read p
		case "$p" in
			[Yy][Ee][Ss]) return 0
		esac
		return 1
	else
		Xdialog --title "$APPTITLE" --yesno "$1" 0 0
	fi
}

# $1-text
splash() {
	if [ -z "$DISPLAY" ]; then
		echo "$1" 
	else
		if [ "$1" ]; then
			[ $SPID ] && kill $SPID
			Xdialog --title "$APPTITLE" --no-buttons --infobox "$1" 0 0 10000000 &
			SPID=$!
		else
			[ $SPID ] && kill $SPID
			SPID=""
		fi
	fi
}


download_gtalk() {
	wget -q "${DOWNLOAD_PATH}"
}

# $1-version
package_gtalk() {
	splash "Making $PKGNAME package, the package will be stored in $HOME"
	mkdir pkg.$$; cd pkg.$$
	
	# extract
	undeb ../${DOWNLOAD_PATH##*/} .
	mv usr/lib usr/lib64
	rm -r etc usr/share
	for p in firefox iceape iceweasel midbrowser xulrunner xulrunner-addons; do
		rm -r usr/lib64/$p
	done
	
	# desc
	mkdir install
cat << EOF > install/slack-desc
$PKGNAME: $PKGNAME $1 (Web browser)  
$PKGNAME:  
$PKGNAME: Official Google Talk plugin.
$PKGNAME: Supports both firefox/seamonkey and possile chromium too.
$PKGNAME: 
$PKGNAME: 
$PKGNAME: 
$PKGNAME: 
$PKGNAME: 
$PKGNAME: 
$PKGNAME:  
EOF

	# make the pkg
	makepkg -c n -l n $HOME/$PKGNAME-$1-$ARCH-official.txz > /dev/null 2>&1
}

# $1-version
install_gtalk() {
	splash "$(eval echo $(gettext 'Installing Google-Talk plugin $1...'))"
	removepkg $PKGNAME
	if ls /var/log/package/$PKGNAME* > /dev/null 2>&1; then
		upgradepkg $HOME/$PKGNAME-$1-$ARCH-official.txz	
	else
		installpkg $HOME/$PKGNAME-$1-$ARCH-official.txz	
	fi
	splash
	msg "$(gettext 'Done. Please restart your browser.')"
}

#### main
get_config
! yesno "\
$(gettext 'Running this program will download, package, and install the latest 
Google Talk plugin for your web browser. If you already have the plugin, it will
be replaced. The newly created package can be found in your $HOME directory.
You can save this package for later, or just delete it.

Continue?
')
" && exit
		
splash "$(gettext 'Downloading Google Talk plugin, please wait ...')"
mkdir -p $WORKDIR; cd $WORKDIR
if download_gtalk; then
	package_gtalk $LATEST
	install_gtalk $LATEST 
else
	splash
	msg "$(gettext  'Failed to download.')"
fi
cd; rm -rf $WORKDIR
