#!/bin/sh

# Copyright (C) 2006-2008 Bart Martens <bartm@knars.be>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# 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/>.

set -e

DOWNLOADFILEMD5="93b7c48eaa492237b807a3ae1de65cf9"
SOFILEMD5="13ce705df5d47422a9192b29827544e8"

TARGETDIR="/usr/lib/flashplugin-nonfree"
TOPDIR="install_flash_player_9_linux"
CACHEDIR="/var/cache/flashplugin-nonfree"

DOWNLOADFILE="install_flash_player_9_linux.tar.gz"
DOWNLOADURL="http://fpdownload.macromedia.com/get/flashplayer/current/$DOWNLOADFILE"

[ ! -f /home/bartm/src/flashplugin-nonfree/bartm_debug ] || DOWNLOADURL="http://127.0.0.1/bartm/$DOWNLOADFILE"

die_hard() {
	echo "$1"
	exit 1
}

md5_match_or_die() {
	echo "$1  $2" | md5sum -c - > /dev/null 2>&1 || die_hard "MD5 checkum mismatch"
}

do_install_amd64() {
	if [ -e /usr/bin/nspluginwrapper ]
	then
		nspluginwrapper -n -i /usr/lib/flashplugin-nonfree/libflashplayer.so || true
	fi
}

do_uninstall_amd64() {
	if [ -e /usr/lib/nspluginwrapper/plugins/npwrapper.libflashplayer.so ] && [ -e /usr/bin/nspluginwrapper ]
	then
		nspluginwrapper -n -r /usr/lib/nspluginwrapper/plugins/npwrapper.libflashplayer.so || true
	fi
}

do_uninstall() {
	do_uninstall_amd64 || true
	rm -f "$TARGETDIR/flashplayer.xpt"
	rm -f "$TARGETDIR/libflashplayer.so"
}

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

pwd | grep -q "^/tmp/flashplugin-nonfree\." || die_hard "current directory not suitable"

[ -d "$CACHEDIR" ] || die_hard "cache directory missing"
[ -d "$TARGETDIR" ] || die_hard "target directory missing"

[ -f "/usr/bin/wget" ] || die_hard "needs \"wget\" installed"

[ $# -eq 1 ] || die_hard "invalid number of parameters"

case $1 in
	--install)
		# continue below
		;;
	--uninstall)
		do_uninstall || die_hard "uninstall failed"
		exit 0
		;;
	*)
		die_hard "unknown: $1"
		;;
esac

[ ! -f "$CACHEDIR/$DOWNLOADFILE" ] || cp -p "$CACHEDIR/$DOWNLOADFILE" "$DOWNLOADFILE"
[ ! -f "$DOWNLOADFILE" ] || echo "$DOWNLOADFILEMD5  $DOWNLOADFILE" | md5sum -c - > /dev/null 2>&1 || rm -f "$DOWNLOADFILE"
[ -f "$DOWNLOADFILE" ] || wget -P "." -v --progress="dot:default" "$DOWNLOADURL" || die_hard "download failed"

md5_match_or_die "$DOWNLOADFILEMD5" "$DOWNLOADFILE"

tar xzf "$DOWNLOADFILE"

md5_match_or_die "$SOFILEMD5" "$TOPDIR/libflashplayer.so"

rm -f "$TARGETDIR/flashplayer.xpt"
mv -f "$TOPDIR/libflashplayer.so" "$TARGETDIR"
chmod 644 "$TARGETDIR/libflashplayer.so"
mv -f "$DOWNLOADFILE" "$CACHEDIR"

do_install_amd64 || true

