#!/usr/bin/bash
# First check if Telegram is downloaded or not
if [ -f "$HOME/.TelegramDesktop/application/Telegram" ]
then
	# If installed then just run it
	"$HOME/.TelegramDesktop/application/Telegram"
else
	# We need to downoad it from telegram.org, for that we need to know the arch we are running on
	arch=$(uname -m)
	tsuffix=''
	if [ "$arch" != "x86_64" ]
	then
		tsuffix='32'
	fi

	# Let's download Telegram
	tmpdir=$(mktemp -d)
	wget https://telegram.org/dl/desktop/linux$tsuffix -O "$tmpdir/telegram.tar.xz" 2>&1 | \
	sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | \
	zenity --progress --auto-close --auto-kill --title="Downloading..."

	# Now we just unpack it and run
	mkdir -p "$HOME/.TelegramDesktop/application"
	tar xf "$tmpdir/telegram.tar.xz" --no-recursion --transform="s/.*\///" -C "$HOME/.TelegramDesktop/application" | \
	  zenity --progress --auto-close --auto-kill --text="Unpacking..." --pulsate && \
	  "$HOME/.TelegramDesktop/application/Telegram"
fi
