#!/bin/dash
# update firefox to latest official version
# jamesbond 2015, 2016
# MIT license
# L18L internationalized to get also localized version

export TEXTDOMAIN=get_app

### config
APPTITLE="$(gettext 'Update Firefox')"
WORKDIR=/tmp/update-firefox.$$
LIBDIR=lib64 # lib for 32-bit
ARCH=x86_64 # i686 for 32-bit


# make sure we cleanup after ourselves
trap '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
			[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
}

### firefox stuff
get_latest_version() {
	# because web scraping is KING!
	wget -qO - https://www.mozilla.org/en-US/firefox/new/ | 
	sed -n '/firefox-[0-9][^-]*-/ { s/.*firefox-\([0-9][^-]*\)-.*/\1/; p}' |
	head -n 1
}

get_current_version() {
	ls -ld /usr/$LIBDIR/firefox-* | tail -n 1 | sed 's/.*firefox-//'
}

# get download path etc
# $1-version
get_download_path() {	
	#FFCHANNEL=latest # or latest-esr # this no longer works, thanks a lot Mozilla :(
	FFCHANNEL=$1
	FF_DOWNLOAD_PATH_DIR="http://ftp.mozilla.org/pub/firefox/releases/$FFCHANNEL/linux-$ARCH"

	FFLANG=en-US # default
    read FFLANG < ${FATDOG_STATE_DIR}/language ; FFLANG=${FFLANG%.*}
    # FFLANG=${FFLANG//_/-} # dash cannot do this
    FFLANG=$(echo ${FFLANG} | tr '_' '-')
    wget --spider -S ${FF_DOWNLOAD_PATH_DIR}/${FFLANG} 2>&1| grep -q '404 Not Found' && FFLANG=${FFLANG%-*}
    wget --spider -S ${FF_DOWNLOAD_PATH_DIR}/${FFLANG} 2>&1| grep -q '404 Not Found' && FFLANG=en-US

	echo "${FF_DOWNLOAD_PATH_DIR}/${FFLANG}/firefox-${1}.tar.bz2"
}

# $1-version
package_firefox() {
	splash "$(eval echo $(gettext 'Making firefox $1 package, the package will be stored in $HOME'))"
	mkdir pkg.$$; cd pkg.$$
	
	# extract
	mkdir -p usr/$LIBDIR/ usr/share/pixmaps usr/bin usr/share/applications
	tar -xf ../firefox.tar.bz2 -C usr/$LIBDIR
	
	# setup symlinks, etc
	mv usr/$LIBDIR/firefox usr/$LIBDIR/firefox-$1
	ln -s firefox-$1 usr/$LIBDIR/firefox
	ln -s /usr/$LIBDIR/firefox/firefox usr/bin/firefox
	ln -s /usr/$LIBDIR/firefox-$VERSION/browser/icons/mozicon128.png \
        usr/share/pixmaps/firefox.png &&
    
	# run firefox as spot
	cat << "EOF" >> usr/bin/firefox-spot &&
#!/bin/dash
SPOT_HOME=$(awk -F: '$1=="spot" {print $6}' /etc/passwd)
#{ chown spot $SPOT_HOME/Downloads;
#chown spot /aufs/devsave/Downloads; } 2> /dev/null
cd $SPOT_HOME/Downloads
exec /usr/bin/run-as-spot /usr/bin/firefox "$@"
EOF
	chmod +x usr/bin/firefox-spot &&
	
	# desktop file
	cat << "EOF" > usr/share/applications/firefox.desktop 
[Desktop Entry]
Version=1.0
Name=Firefox Browser
GenericName=Web Browser
Comment=Your web, the way you like it
Exec=firefox-spot %U
Icon=firefox.png
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

	# desc
	mkdir install
	cat << EOF > install/slack-desc
firefox: firefox $1 (Web browser)  
firefox:  
firefox: Official Firefox web browser from Mozilla.
firefox: 
firefox: 
firefox: 
firefox: 
firefox: 
firefox: 
firefox: 
firefox:  
EOF
	# make the pkg
	makepkg -c n -l n $HOME/firefox-$1-$ARCH-official.txz > /dev/null 2>&1
}

# $1-version
install_firefox() {
	splash "$(eval echo $(gettext 'Upgrading firefox to $1...'))"
	removepkg firefox
	installpkg $HOME/firefox-$1-$ARCH-official.txz
	splash
	msg "$(gettext 'Done.')"
}

#### main
check_root
! yesno "\
$(gettext 'Running this program may replace your Firefox with the OFFICIAL binary
from Mozila, instead of Fatdog-build one.') $(gettext 'It should work, but in some
rare cases Fatdog may be missing some libraries that prevent this 
official from running.') $(gettext 'Are you sure you want to continue?')
" && exit
splash "$(gettext 'Checking latest released version ...')"
CURRENT=$(get_current_version)
if ! LATEST=$(get_latest_version); then
	splash
	msg "$(gettext 'Cannot connect to Mozilla website. Leaving now.')"
	exit
fi
splash
#echo CURRENT=$CURRENT LATEST=$LATEST

if [ "$LATEST" = "$CURRENT" ]; then
	msg "$(eval echo $(gettext 'You are already running the latest version $LATEST.'))"
else
	if [ -z $CURRENT ]; then
		! yesno "$(gettext 'You do not seem to have firefox installed.')
$(gettext 'Do you want to install it?')" && exit
	fi
	splash "$(eval echo $(gettext 'Downloading firefox $LATEST, please wait ...'))"
	DOWNLOAD_PATH=$(get_download_path $LATEST)
	mkdir $WORKDIR; cd $WORKDIR
	if wget -qO firefox.tar.bz2 "$DOWNLOAD_PATH"; then
		package_firefox $LATEST
		install_firefox	$LATEST	
	else
		splash
		msg "$(gettext 'Failed to download.')"
	fi
fi
