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

export TEXTDOMAIN=get_app
. gettext.sh

### config
APPTITLE="$(gettext 'Update Seamonkey')"
WORKDIR=/tmp/update-seamonkey.$$
OUTPUT_DIR=${OUTPUT_DIR:-/root}
SM_LANG=${SM_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 www.seamonkey-project.org; 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
		splash "$(gettext "Installing $PKG, please wait...")"
		if ! slapt-get --install $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
}



#### seamonkey specific stuff #####

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

# output: stdout: latest non-beta version
get_latest_version() {
	curl -s https://archive.mozilla.org/pub/seamonkey/releases/ |
	html2 |
	sed '/href/!d; s/.*releases\///; 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/seamonkey/releases/$VER/linux-x86_64/"
}

# input $VER, $SM_LANG, $ARCH, outputs $TARBALL, and $DL_URL
get_download_path() {
	[ -z $VER ] && die "$(gettext "Cannot find latest version.")"
	TARBALL=seamonkey-${VER}.${SM_LANG}.linux-$ARCH.tar.bz2
	DL_URL="https://archive.mozilla.org/pub/seamonkey/releases/$VER/linux-x86_64/$SM_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_sm() {
	mkdir $WORKDIR
	curl "$DL_URL" > "$WORKDIR/$TARBALL"
}

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

	cat > ./install/slack-desc << EOF
seamonkey: seamonkey $VER (Web browser)  
seamonkey:  
seamonkey: Official Seamonkey web browser from Seamonkey Project.
seamonkey: 
seamonkey: http://seamonkey-project.org/
seamonkey: 
seamonkey: 
seamonkey: 
seamonkey: 
seamonkey: 
seamonkey: 
EOF

	# desktop files
	cat << "EOF" > ./usr/share/applications/seamonkey.desktop
[Desktop Entry]
Version=1.0
Name=Seamonkey Browser
GenericName=Web Browser
Comment=Your web, the way you like it
Exec=seamonkey-spot %U
Icon=seamonkey48
Terminal=false
Type=Application
MimeType=text/html;text/xml;application/xhtml+xml;application/vnd.mozilla.xul+xml;text/mml;x-scheme-handler/http;x-scheme-handler/https;
StartupNotify=false
X-MultipleArgs=false
X-Desktop-File-Install-Version=0.16
Categories=WebBrowser;
Encoding=UTF-8
EOF

	# desktop files
	cat << "EOF" > ./usr/share/applications/seamonkey-addressbook.desktop
[Desktop Entry]
Encoding=UTF-8
Name=SeaMonkey Addressbook
Icon=contact48
Comment=SeaMonkey Addressbook
Exec=seamonkey-spot -addressbook
Terminal=false
Type=Application
Categories=X-Personal;Office
GenericName=SeaMonkey Addressbook
EOF

	# desktop files
	cat << "EOF" > ./usr/share/applications/seamonkey-composer-html-editor.desktop
[Desktop Entry]
Encoding=UTF-8
Name=SeaMonkey Composer html editor
Icon=mozicon48
Comment=SeaMonkey Composer html editor
Exec=seamonkey -edit
Terminal=false
Type=Application
Categories=X-Document;
GenericName=SeaMonkey Composer html editor
EOF

	# desktop files
	cat << "EOF" > ./usr/share/applications/seamonkey-mail.desktop
[Desktop Entry]
Encoding=UTF-8
Name=SeaMonkey mail
Icon=email48
Comment=SeaMonkey mail
Exec=seamonkey-spot -mail
Terminal=false
Type=Application
Categories=X-Internet;Office
GenericName=SeaMonkey mail
EOF

	OUTPUT_PKG=$OUTPUT_DIR/seamonkey-$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 Seamonkey with the OFFICIAL binary
from Seamonkey 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
SM_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 Seamonkey $VER ...")"
download_sm
splash "$(eval_gettext "Packaging Seamonkey $VER ...")"
package_sm
splash "$(eval_gettext "Updating Seamonkey $VER ...")"
removepkg seamonkey
installpkg $OUTPUT_PKG
splash
msg "$(eval_gettext "Seamonkey $VER installed. A copy of the package is stored in $OUTPUT_PKG")"
