#!/bin/sh

# Copyright (C) 2006-2013 Bart Martens <bartm@knars.be>
# Copiright (C) 2014 Andrey Cherepanov <cas@altlinux.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

script_version="1.5.3"

set -e

return_0() {
	return 0
}

trap "return_0" 0

die_hard() {
	echo "ERROR: $1" >&2
	echo "More information might be available at:" >&2
	echo "  http://altlinux.org/PepperFlash" >&2
	exit 1
}

[ `whoami` = "root" ] || die_hard "must be root"

show_usage() {
	echo "Usage:"
	echo "  update-pepperflash --install"
	echo "  update-pepperflash --uninstall"
	echo "  update-pepperflash --status"
	echo "Additional options:"
	echo "  --verbose"
	echo "  --quiet"
	echo "  --clean"
	echo "  --version"
	exit 1
}

attr() {
        sed 's/^.*="\(.*\)"/\1/'
}

getopt_temp=`getopt -o iusfvq --long install,uninstall,status,fast,verbose,quiet,beta,unstable,unverified,clean,version \
	-n 'update-pepperflash' -- "$@"` || show_usage
eval set -- "$getopt_temp" || show_usage

ACTION=none
fast=no
verbose=no
quiet=no
variant=stable
verified=yes

cachedir=/var/cache/pepperflash
mkdir -p "$cachedir"

while [ true ]
do
	case "$1" in
		-i|--install)
			ACTION="--install"
			shift
			;;
		-u|--uninstall)
			ACTION="--uninstall"
			shift
			;;
		-s|--status)
			ACTION="--status"
			shift
			;;
		-f|--fast)
			fast=yes
			shift
			;;
		-v|--verbose)
			verbose=yes
			shift
			;;
		-q|--quiet)
			quiet=yes
			shift
			;;
		--beta)
			variant=beta
			shift
			;;
		--unstable)
			variant=unstable
			shift
			;;
		--unverified)
			verified=no
			shift
			;;
		--clean|--version)
			ACTION="$1"
			shift
			;;
		--)
			shift
			break
			;;
		*)
			echo "Internal error!"
			exit 1
			;;
	esac
done

[ "$ACTION" != "none" -a $# -eq 0 ] || show_usage
[ "$quiet" != "yes" ] || verbose=no

[ "$verbose" != "yes" ] || echo "options : $getopt_temp"

latestfile=latest-$variant-verified.txt
[ "$verified" != "no" ] || latestfile=latest-$variant.txt

UNPACKDIR=`mktemp -d /tmp/pepperflash.XXXXXXXXXX` || die_hard "mktemp failed"
echo "$UNPACKDIR" | grep -q "^/tmp/pepperflash\." || die_hard "paranoia"
cd "$UNPACKDIR" || die_hard "cd failed"

[ "$verbose" != "yes" ] || echo "temporary directory: $UNPACKDIR"

do_cleanup() {
	[ "$verbose" != "yes" ] || echo "cleaning up temporary directory $UNPACKDIR ..."
	cd /
	echo "$UNPACKDIR" | grep -q "^/tmp/pepperflash\." || die_hard "paranoia"
	rm -rf "$UNPACKDIR"
}

die_hard_with_a_cleanup() {
	return_0
	do_cleanup
	die_hard "$1"
}

trap "die_hard_with_a_cleanup interrupted" INT

wgetquiet=' -q '
wgetfast='-t 3 -T 15 -c'
wgetalways=' -nd -P . '
#wgetprogress=' -v --progress=dot:default '
wgetprogress='-v'

if [ "$ACTION" = "--install" -o "$ACTION" = "--status" ]
then
	installed="`sed -nrz '/^.*LNX [0-9,]+$/p' $(getconf LIBDIR)/pepper-plugins/libpepflashplayer.so 2>/dev/null |sed -n "s/^.*LNX //p"|tr , .`"

	# Create file with versions
	localrpm="$(ls -1 $cachedir/*.rpm 2>/dev/null | tail -n1)"
	localrpmver=""
	[ -n "$localrpm" ] && localrpmver="$(rpm -q --qf "%{version}" -p "$localrpm")"
	echo "$localrpmver" > $cachedir/$latestfile
	echo "$installed"  >> $cachedir/$latestfile

	if [ -f $cachedir/$latestfile ]
	then
		chromeversion=`head -n 1 $cachedir/$latestfile`
		flashversion=`tail -n 1 $cachedir/$latestfile`
	else
		chromeversion=0
		flashversion=0
	fi

	# YUM repository: https://dl.google.com/linux/chrome/rpm/stable/x86_64/repodata/primary.xml.gz

	# Get architecture
	arch="$(uname -m)"
        [ "$arch" != "x86_64" ] && arch="i386"  # i386 for 32-bit and x86_64 for 64-bit

	target="https://dl.google.com/linux/chrome/rpm/stable/$arch/repodata/primary.xml.gz"
	if [ "$(curl -4 --write-out %{http_code} -s "$target" -o /dev/null)" != "200" ]; then
                die_hard "Network is unavailable"
        fi

	# Get XML node for google-chrome-stable from official YUM repository  from Google
	pkg="$(curl -4 -s "$target" 2>/dev/null | gunzip | sed 's/xmlns/ignore/' | xmllint --xpath '/metadata/package[contains(name,"google-chrome-stable")]' - 2>/dev/null)"

	[ -z "$pkg" ] && die_hard "Error parse metadata from $target"

	# Fill Chrome version, checksum and file name
	newchromeversion="$(echo "$pkg" | xmllint --xpath '/package/version/@ver' - 2>/dev/null | attr)"
	checksum="$(echo "$pkg" | xmllint --xpath '/package/checksum/text()' - 2>/dev/null)"
	rpmfile="$(echo "$pkg" | xmllint --pretty 0 --xpath '/package/location/@href' - 2>/dev/null | attr)"
	downloadurl="https://dl.google.com/linux/chrome/rpm/stable/$arch/$rpmfile"
	rpmurl="$downloadurl"

	if [ "$chromeversion" = "$newchromeversion" ]
	then
		if [ -n "$installed" ]; then
			upstream="$installed"
		else
			upstream="(from google-chrome-stable-$newchromeversion)"
		fi
	else
		chromeversion=`head -n 1 $cachedir/$latestfile`
		flashversion=`tail -n 1 $cachedir/$latestfile`

		upstream="(from google-chrome-stable-$newchromeversion)"
	fi
fi

case "$ACTION" in

	--install)
		[ "$verbose" != "yes" ] || echo "selected action = $ACTION"

		[ "$upstream" != "" ] || die_hard_with_a_cleanup "failed to determine upstream version"

		if [ "$installed" != "" -a "$upstream" != "" -a "$installed" = "$upstream" ]
		then

			[ "$verbose" != "yes" ] || echo "upstream version $upstream is already installed"

		else

			if [ -f $cachedir/$rpmfile ]
			then
				cp -p $cachedir/$rpmfile .
			fi
	
			if [ ! -f $rpmfile ]
			then
				[ "$verbose" != "yes" ] || echo "Download $rpmfile"
				wgetoptions="$wgetalways $wgetprogress"
				[ "$quiet" != "yes" ] || wgetoptions="$wgetquiet $wgetalways"
				[ "$fast" != "yes" ] || wgetoptions="$wgetoptions $wgetfast"
				wgetoptions="$wgetoptions -O $UNPACKDIR/$rpmfile" # to change wget message : Saving to ...
	
				wget $wgetoptions $rpmurl || die_hard_with_a_cleanup "wget failed to download $rpmurl"
	
				[ `sha1sum $rpmfile|sed -e "s, .*,,"` = "$checksum" ] || die_hard_with_a_cleanup "rejecting $rpmfile : wrong sha1sum"
			fi
	
			# Plugin and manifest file names in RPM file
			pluginfile="./opt/google/chrome/PepperFlash/libpepflashplayer.so"
			manifestfile="./opt/google/chrome/PepperFlash/manifest.json"

			# Extract plugin from RPM file
			[ "$verbose" != "yes" ] || echo "Extract plugin from RPM file"
			rpm2cpio "$rpmfile" | cpio -idmv "$pluginfile" "$manifestfile" &>/dev/null

			install -D -m 0644 $pluginfile $(getconf LIBDIR)/pepper-plugins/libpepflashplayer.so
			install -D -m 0644 $manifestfile $(getconf LIBDIR)/pepper-plugins/manifest.json

			# Move rpm file to cache
			mv $rpmfile $cachedir
		fi

		# Cleanup cache
		find "$cachedir" -mindepth 1 -maxdepth 1 -type f -name 'google-chrome*.rpm' -not -name "$rpmfile" -delete

		[ "$verbose" != "yes" ] || echo "Set path to plugin to chromium configuration file /etc/chromium/default"

		if [ -e /etc/chromium/default -a -z "$(grep pepflash /etc/chromium/default)" ]; then
			cat >> /etc/chromium/default << '__DEFAULT_CONF__'
# PepperFlash support (see http://www.altlinux.org/PepperFlash)
flashso="$(getconf LIBDIR)/pepper-plugins/libpepflashplayer.so"

if [ -f $flashso ]
then
        flashversion="`sed -nrz '/^.*LNX [0-9,]+$/p' $flashso|sed -n "s/^.*LNX //p"|tr , .`"
        CHROMIUM_FLAGS="$CHROMIUM_FLAGS --ppapi-flash-path=$flashso --ppapi-flash-version=$flashversion"
fi
__DEFAULT_CONF__
		fi

		# Upgrade version detection for new plugin version
		if [ -e /etc/chromium/default -a -n "$(grep '\^LNX' /etc/chromium/default)" ]; then
			subst 's/\^LNX/^.*LNX/' /etc/chromium/default
		fi

		# Fix path to moved Pepper plugin to %_libdir/pepper-plugins
		if [ -e /etc/chromium/default -a -n "$(grep 'LIBDIR)/browser-plugins/' /etc/chromium/default)" ]; then
			subst 's,LIBDIR)/browser-plugins/,LIBDIR)/pepper-plugins/,' /etc/chromium/default
		fi

		[ "$verbose" != "yes" ] || echo "end of action $ACTION"

		;;

	--uninstall)
		[ "$verbose" != "yes" ] || echo "selected action = $ACTION"

		[ "$verbose" != "yes" ] || echo "removing files ..."

		if [ "$verbose" != "yes" ]; then
			rm -f $(getconf LIBDIR)/pepper-plugins/{libpepflashplayer.so,manifest.json} $cachedir/*.rpm $cachedir/*.txt
		else
			rm -fv $(getconf LIBDIR)/pepper-plugins/{libpepflashplayer.so,manifest.json} $cachedir/*.rpm $cachedir/*.txt
		fi

		[ "$verbose" != "yes" ] || echo "end of action $ACTION"

		;;

	--status)
		[ "$verbose" != "yes" ] || echo "selected action = $ACTION"

		echo "Flash Player version installed on this system  : $installed"
		echo "Flash Player version available on upstream site: $upstream"

		[ "$verbose" != "yes" ] || echo "end of action $ACTION"

		;;

	--clean)
		p=""
		[ "$verbose" = "yes" ] && p="v"
		rm -f $cachedir/*.rpm
		exit 0

		;;

	--version)
		echo "$script_version"
		exit 0;

		;;

	*)

		do_cleanup
		show_usage

		;;

esac

do_cleanup

[ "$verbose" != "yes" ] || echo "end of update-pepperflash"

