#!/bin/sh
# Name: WPS installer
# Version: 1.4
# Description: install KingSoft WPS to your openSUSE.
# Author: Marguerite Su <marguerite@opensuse.org>
# License: GPL-3.0+

# force root
if [ "`id -u`" != "0" ]; then
 echo "error: You must be root to use this program!"
 exit 1
fi

WPS_VER="10.1.0.5672"
WPS_AVER="a21"

if [ `uname -m` == "x86_64" ] ; then
 WPS_ARCH="x86_64"
else
 WPS_ARCH="x86"
fi

WPS_TAR="wps-office_${WPS_VER}~${WPS_AVER}_${WPS_ARCH}.tar.xz"

WPS_URL="http://kdl.cc.ksosoft.com/wps-community/download/${WPS_AVER}/${WPS_TAR}"

TMP_DIR=/tmp

WPS_DIR=wps-office_${WPS_VER}_${WPS_ARCH}

WPS_DESTDIR=/usr/share/wps-office/

WPS_FONTDIR=/usr/share/fonts/wps-office/

pushd $TMP_DIR &> /dev/null
	# clean old tar first
	rm -rf $WPS_TAR
	if [ ! -f ./${WPS_TAR} ] ; then
		echo "Downloading proprietary binary from Kingsoft (100+ MB)..."
		wget $WPS_URL;
		echo "Done!"
	fi
	echo "Unpacking...it'll take some time"
	tar -xf $WPS_TAR
	rm -rf $WPS_TAR
	echo "Done!"
	pushd $WPS_DIR	&> /dev/null
		
		# install data
		if [ ! -d $WPS_DESTDIR ] ; then
			mkdir -p $WPS_DESTDIR;
		fi

		# rename whitespace to _
		pushd office6 &> /dev/null
		  find . -type d | sort -r | while read d;  do ( cd "$d"; for i in *; do test -a  "${i// /_}" || mv "$i" "${i// /_}" ; done ; ); done &> /dev/null
		popd &> /dev/null

		echo "Copying files...Ultra slow..."

		cp -r office6 $WPS_DESTDIR
		
		# install scripts
		sed -i "5d" ./{et,wps,wpp}
		sed -i "5i\gBinPath=${WPS_DESTDIR}" ./{et,wps,wpp}
		cp -r ./{et,wps,wpp} /usr/bin

		echo "Done!"

		# install fonts
		if [ ! -d $WPS_FONTDIR ] ; then
			mkdir -p $WPS_FONTDIR;
		fi

		echo "Copying fonts..."
		cp -r fonts/*.TTF ${WPS_FONTDIR}
		echo "Done!"
		echo "Installing fontconfig files..."
		cp -r fontconfig/40-wps-office.conf /usr/share/fontconfig/conf.avail/
		echo "Done!"
		echo "Running fc-cache...Ultra slow"
		fc-cache -f
		echo "Done!"

		# install desktop files
		cp -r resource/applications/*.desktop /usr/share/applications/
		/usr/bin/update-desktop-database /usr/share/applications/ &>/dev/null
		
		# install icons
		pushd resource/icons/hicolor &> /dev/null
			for i in "16 32 48 256"; do
				cp -r ${i}x${i}/apps/*.png /usr/share/icons/hicolor/${i}x${i}/apps/
				cp -r ${i}x${i}/mimetypes/*.png /usr/share/icons/hicolor/${i}x${i}/mimetypes/
			done
		popd &> /dev/null
		/usr/bin/gtk-update-icon-cache --quiet --force /usr/share/icons/hicolor/

		# install mimetypes
		cp -r resource/mime/packages/*.xml /usr/share/mime/packages/
		/usr/bin/update-mime-database /usr/share/mime/

	popd &> /dev/null
# clean
rm -rf $WPS_DIR 
echo "Congratulations! Installation succeed!"
popd &> /dev/null
