#!/bin/bash
# download and update thunderbird to latest official version
# need to install gtk3, libapulse
# requires bash 4.3 or newer for arrays and nameref
# jamesbond 2020, 2022
# MIT license

export TEXTDOMAIN=get_app
. gettext.sh

### config
APPTITLE="$(gettext 'Get Thunderbird')"
WORKDIR=/tmp/update-thunderbird.$$
OUTPUT_DIR=${OUTPUT_DIR:-/root}
TB_LANG=${TB_LANG:-en-US}

declare -A LANGUAGES=(
   [English (US)]=en-US
   [Acholi]=ach
   [Afrikaans]=af
   [Albanian]=sq
   [Arabic]=ar
   [Aragonese]=an
   [Armenian]=hy-AM
   [Assamese]=as
   [Asturian]=ast
   [Azerbaijani]=az
   [Basque]=eu
   [Belarusian]=be
   [Bengali (Bangladesh)]=bn-BD
   [Bengali (India)]=bn-IN
   [Bosnian]=bs
   [Breton]=br
   [Bulgarian]=bg
   [Catalan]=ca
   [Chinese (Simplified)]=zh-CN
   [Chinese (Traditional)]=zh-TW
   [Croatian]=hr
   [Czech]=cs
   [Danish]=da
   [Dutch]=nl
   [English (British)]=en-GB
   [English (South African)]=en-ZA
   [Esperanto]=eo
   [Estonian]=et
   [Finnish]=fi
   [French]=fr
   [Frisian]=fy-NL
   [Fulah]=ff
   [Gaelic (Scotland)]=gd
   [Galician]=gl
   [German]=de
   [Georgian]=ka
   [Greek]=el
   [Gujarati (India)]=gu-IN
   [Hebrew]=he
   [Hindi (India)]=hi-IN
   [Hungarian]=hu
   [Icelandic]=is
   [Indonesian]=id
   [Irish]=ga-IE
   [Italian]=it
   [Japanese]=ja
   [Kannada]=kn
   [Kazakh]=kk
   [Khmer]=km
   [Korean]=ko
   [Latvian]=lv
   [Ligurian]=lij
   [Lithuanian]=lt
   [Lower Sorbian]=dsb
   [Macedonian]=mk
   [Maithili]=mai
   [Malay]=ms
   [Malayalam]=ml
   [Marathi]=mr
   [Norwegian (BokmÃ¥l)]=nb-NO
   [Norwegian (Nynorsk)]=nn-NO
   [Oriya]=or
   [Persian]=fa
   [Polish]=pl
   [Portuguese (Brazilian)]=pt-BR
   [Portuguese (Portugal)]=pt-PT
   [Punjabi (India)]=pa-IN
   [Romanian]=ro
   [Romansh]=rm
   [Russian]=ru
   [Serbian]=sr
   [Sinhala]=si
   [Slovak]=sk
   [Slovenian]=sl
   [Songhai]=son
   [Spanish (Argentina)]=es-AR
   [Spanish (Chile)]=es-CL
   [Spanish (Mexico)]=es-MX
   [Spanish (Spain)]=es-ES
   [Swedish]=sv-SE
   [Tamil]=ta
   [Telugu]=te
   [Thai]=th
   [Turkish]=tr
   [Ukrainian]=urk
   [Upper Sorbian]=hsb
   [Uzbek]=uz
   [Vietnamese]=vi
   [Welsh]=cy
   [Xhosa]=xh
)

# make sure we cleanup after ourselves
trap 'cd $HOME; rm -rf $WORKDIR; exit' 0 INT HUP TERM


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

# are we root?
check_root() {
	if [ $(id -u) -ne 0 ]; then
		msg "$(gettext 'You must be root.')"
		exit 1
	fi
}

# $1-text, returns true/false
yesno() {
	local p
	if [ -z "$DISPLAY" ]; then
		printf "%s\nType [yes] to continue: " "$1"
		read p
		case "${p,,}" in
			yes) 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 100000000 &
            SPID=$!
        else
            [ $SPID ] && kill $SPID
            SPID=""
        fi
    fi
}

# $@ - words
sortwords() {
	for p; do echo $p; done | sort -u
}

# $1-text $2-selections $3-default
choose() {
	local -n ITEMS=${2}
	local value index xdialog_items="" state
	if [ -z "$DISPLAY" ]; then
		echo "$1"
		OIFS="$IFS"; IFS=$'\n'
		select index in $(sortwords "${!ITEMS[@]}"); do
			#echo Selected Lang is $index, its code is ${ITEMS["$index"]}
			echo ${ITEMS["$index"]}
			break
		done
		IFS="$OIFS"
	else
		OIFS="$IFS"; IFS=$'\n'
		for index in $(sortwords "${!ITEMS[@]}"); do
			[ "$index" = "$3" ] && state=on || state=off
			xdialog_items="$xdialog_items \"${ITEMS[$index]}\" \"$index\" $state"
		done
		IFS="$OIFS"
		eval Xdialog --title \"$APPTITLE\" --stdout --no-tags --radiolist \"$1\" 30 50 10 $xdialog_items
	fi
}

check_online () {
    if ! wget -q --spider https://www.thunderbird.net/; then
        msg "$gettext 'No connection to internet. Leaving now.'"
        exit
    fi    
}

# $1-pkgname (no space)
download_support_libraries() {
	local PKG=$1
	if ! slapt-get --installed | grep -q "^$PKG.*$ARCH"; then
		splash "$(gettext "Updating package list, please wait...")"
		slapt-get --update --no-prompt
		splash "$(gettext "Installing $PKG, please wait...")"
		if ! slapt-get --install --no-prompt $PKG; then
			splash
			msg "$(gettext "Failed to install $PKG.")"
			exit 1
		fi
	fi
}

# $@ - message
die() {
	msg "$*"
	exit 1
}

# input: $AVAIL_LANGS, output $LANGUAGES
trim_languages() {
	local p exist i
	#set -x
	#echo "${!LANGUAGES[@]}"
	
	for i in "${!LANGUAGES[@]}"
	do			
		#echo "key  : $i"
		#echo "value: ${LANGUAGES[$i]}"

		exist=
		for p in $AVAIL_LANGS; do
			[ "$p" = "${LANGUAGES[$i]}" ] && exist=1 && break
		done
		[ $exist ] || unset LANGUAGES["$i"]
	done
	#echo "${!LANGUAGES[@]}"
}

# output: $ARCH and $LIBDIR
get_sysinfo() {
	ARCH=$(uname -m)
	case $ARCH in
		x86_64) LIBDIR=lib64 ;;
		i686) LIBDIR=lib ;;
	esac
}



#### thunderbird specific stuff #####

# input: $LIBDIR
get_current_version() {
	local p
	if [ -L /usr/$LIBDIR/thunderbird ]; then
		p=/usr/$LIBDIR/$(readlink usr/$LIBDIR/thunderbird)
		[ -e $p ] && echo $p | sed 's/.*thunderbird-//'
	fi
}

# output: stdout: latest non-beta version
get_latest_version() {
	curl -s https://archive.mozilla.org/pub/thunderbird/releases/ |
	html2 |
	sed '/href/!d; s/.*releases\///; s/.*latest\///; s/.*latest-beta\///; s/.*custom-updates\///; s/.$//; /b/d; /READ/d' |
	sort -rV | head -n1 
}

# input $VER, outputs $LANG_URL
get_arch_lang_url() {
	[ -z $VER ] && die "$(gettext "Cannot find latest version.")"
	LANG_URL="https://archive.mozilla.org/pub/thunderbird/releases/$VER/linux-x86_64/"
}

# input $VER, $TB_LANG, $ARCH, outputs $TARBALL, and $DL_URL
get_download_path() {
	[ -z $VER ] && die "$(gettext "Cannot find latest version.")"
	TARBALL=thunderbird-${VER}.tar.bz2
	DL_URL="https://archive.mozilla.org/pub/thunderbird/releases/$VER/linux-x86_64/$TB_LANG/$TARBALL"
}

# input $LANG_URL, output AVAIL_LANGS
get_available_languages() {
	AVAIL_LANGS="$(curl -s $LANG_URL | sed '/releases/!d; s/^.*">//; s/\/<.*//')"
}

# input $WORKDIR, $TARBALL
download_tb() {
	mkdir $WORKDIR
	curl "$DL_URL" > "$WORKDIR/$TARBALL"
}

# input $WORKDIR, $TARBALL, $VER, $LIBDIR, $ARCH, $OUTPUT_DIR, output $OUTPUT_PKG
package_tb() {
	mkdir $WORKDIR/tb-setup; cd $WORKDIR/tb-setup
	
	mkdir -p ./usr/$LIBDIR ./usr/bin ./install ./usr/share/applications ./usr/share/icons
	tar -xf $WORKDIR/$TARBALL -C ./usr/$LIBDIR
	cp ./usr/$LIBDIR/thunderbird/chrome/icons/default/default256.png ./usr/share/icons/thunderbird.png	
	mv ./usr/$LIBDIR/thunderbird ./usr/$LIBDIR/thunderbird-$VER
	ln -s thunderbird-$VER ./usr/$LIBDIR/thunderbird
	cat > ./usr/bin/thunderbird << EOF
#!/bin/dash
if type apulse > /dev/null; then
	exec apulse /usr/$LIBDIR/thunderbird/thunderbird "\$@"
else
	exec /usr/$LIBDIR/thunderbird/thunderbird "\$@"
fi
EOF
	chmod +x ./usr/bin/thunderbird
	ln -s program-spot ./usr/bin/thunderbird-spot # assume already installed

	cat > ./install/slack-desc << EOF
thunderbird: thunderbird $VER (Mail Client)
thunderbird:  
thunderbird: Official Thunderbird Mail Client from Thunderbird Project.
thunderbird: 
thunderbird: https://www.thunderbird.net/
thunderbird: 
thunderbird: 
thunderbird: 
thunderbird: 
thunderbird: 
thunderbird: 
EOF

	# desktop files
	cat << "EOF" > ./usr/share/applications/thunderbird.desktop
[Desktop Entry]
Version=1.0
Name=Thunderbird Mail
Comment=Send and receive mail with Thunderbird
GenericName=Mail Client
Exec=thunderbird-spot %u
Terminal=false
Type=Application
Icon=thunderbird
Categories=Network;Email;
MimeType=application/xhtml+xml;text/xml;application/xhtml+xml;application/xml;application/rss+xml;x-scheme-handler/mailto;
StartupNotify=true
EOF

	OUTPUT_PKG=$OUTPUT_DIR/thunderbird-$VER-$ARCH-official.txz
	makepkg -c n -l n $OUTPUT_PKG
}


########### main #########

splash "$(gettext "Checking online connection...")"
check_root
check_online
splash
! yesno "\
$(gettext 'Running this program may replace your Thunderbird with the OFFICIAL binary
from Thunderbird Project, instead of Fatdog-build one.') $(gettext 'Recent versions require
GTK3 libraries and apulse library to be installed.') $(gettext 'In addition, 
there may be other libraries that missing from Fatdog that prevent this 
official binary from running.') $(gettext 'Are you sure you want to continue?')
" && exit

# get latest version
get_sysinfo
splash "$(gettext "Finding latest version ...")"
VER=$(get_latest_version)
splash
[ -z $VER ] && die "$(gettext "Cannot find latest version.")"
[ "$VER" = "$(get_current_version)" ] && die "$(gettext "You are already running the latest version.")"

# choose language
splash "$(gettext "Checking available languages ...")"
get_arch_lang_url
get_available_languages
trim_languages
splash
TB_LANG=$(choose "Choose languages" LANGUAGES "English (US)") || exit
get_download_path

# install support libraries
splash "$(gettext "Downloading and installing support libraries...")"
download_support_libraries gtk3
download_support_libraries libapulse
splash

# download, package and install
splash "$(eval_gettext "Downloading Thunderbird $VER ...")"
download_tb
splash "$(eval_gettext "Packaging Thunderbird $VER ...")"
package_tb
splash "$(eval_gettext "Updating Thunderbird $VER ...")"
removepkg thunderbird
installpkg $OUTPUT_PKG
splash
msg "$(eval_gettext "Thunderbird $VER installed. A copy of the package is stored in $OUTPUT_PKG")"
