#!/bin/sh

killall firefox.exe

if [ "${PACKAGE}" = "" ]; then
	PACKAGE="wine-browser-installer";
fi

INSTDIR="/usr/share/wine-browser-installer";
WINE_BROWSER="${HOME}/.wine-browser";
OTHER_SUMS="${INSTDIR}/${PACKAGE}.sha256sums";
LOCAL_SUMS="${WINE_BROWSER}/wine-browser.sha256sums";
GLOBAL_SUMS="${INSTDIR}/wine-browser-installer.sha256sums";
WINE="/opt/wine-compholio/bin/wine";
SHOWDEBUG="0";
RELAYLOG="0";
if [ "$1" = "" ]; then
	URL="http://www.katsomo.fi";
	else URL="$1"
fi

if [ "${SERVICE}" = "" ]; then
	SERVICE=$(gettext "On Demand Wine Browser");
fi

# Enable translation capabilities
. gettext.sh
export TEXTDOMAIN="netflix-desktop";
export TEXTDOMAINDIR="/usr/share/locale";
# General strings that are translatable
gettext_download_missing=$(eval_gettext "Not all of the components required by \$SERVICE were downloaded, would you like to download them now? (requires an Internet connection and sudo permissions)");
gettext_fonts_needed=$(gettext "MS true type fonts are not properly installed, would you like to download and install them now? (requires an Internet connection and sudo permissions)");
gettext_fonts_still_needed=$(eval_gettext "It appears that you still have not installed the MS true type fonts, you need to accept the license agreement and install these fonts for \$SERVICE to work properly.");
gettext_compositing_error=$(eval_gettext "Compositing is disabled in the X11 configuration file, please enable compositing support and relaunch \$SERVICE.");

# Version comparison
vercomp () {
	if [ "$1" = "$2" ]; then
		RET="0";
	elif [ "$1" = "`echo -e "$1\n$2" | sort -V | head -n1`" ]; then
		RET="1";
	else
		RET="-1";
	fi
	echo "${RET}";
}

# Make sure that all the necessary files are installed.
files_missing=1;
while [ "$files_missing" -eq "1" ]; do
	files_missing=0;
	SUMS="/tmp/wine-browser.$$.sha256sums";
	cat "${GLOBAL_SUMS}" "${OTHER_SUMS}" > "${SUMS}";
	while read desired_checksum filename permissions url; do
		if [ ! -f "${INSTDIR}/${filename}" ]; then
			files_missing=1;
		fi
	done < "${SUMS}";
	rm "${SUMS}";
	if [ "$files_missing" -eq "1" ]; then
		zenity --question --title="${SERVICE}" --text="${gettext_download_missing}" --ok-label="Yes" --cancel-label="No";
		RET=$?;
		if [ "$RET" -eq "1" ]; then
			exit;
		fi
		# Use a separate script to download the file (gksudo takes forever to exit each time)
		gksudo "${INSTDIR}/download-missing-files" ${PACKAGE} "${SERVICE}";
	fi
done

# Make sure that the filesystem supports extended file attributes
"${INSTDIR}/test-xattr" "${WINE_BROWSER}";
XATTR="$?";
if [ "${XATTR}" -ne "0" ]; then
	if [ "${XATTR}" -eq "1" ]; then
		MESSAGE=$(eval_gettext "Unable to test extended attributes at location '\${WINE_BROWSER}'.");
	elif [ "${XATTR}" -eq "2" ]; then
		MESSAGE=$(gettext "It appears that you do not have extended file system attributes enabled, please enable the user_xattr option for your filesystem and try again.");
	else
		MESSAGE=$(gettext "An unexpected error code was returned when testing for extended file system attributes.");
	fi
	zenity --warning --title="${SERVICE}" --text "${MESSAGE}";
	exit;
fi

# Make sure that compositing is not disabled in the X11 configuration file
if [ -f /etc/X11/xorg.conf ]; then
	COMPDISABLED=`cat /etc/X11/xorg.conf | sed '/.*Option[ \t]*"Composite"/!d' | grep -ic disable`;
	if [ "${COMPDISABLED}" -ne "0" ]; then
		zenity --warning --title="${SERVICE}" --text "${gettext_compositing_error}";
		exit;
	fi
fi

# Make sure that the MS core true type fonts are installed
COREFONTS=`debconf-show ttf-mscorefonts-installer 2>/dev/null | grep "msttcorefonts/accepted-mscorefonts-eula: true"`;
if [ "${COREFONTS}" = "" ]; then
	zenity --question --title="${SERVICE}" --text="${gettext_fonts_needed}" --ok-label="Yes" --cancel-label="No";
	RET=$?;
	if [ "$RET" -eq "1" ]; then
		exit;
	fi
	gksudo ${INSTDIR}/install-fonts;
	COREFONTS=`debconf-show ttf-mscorefonts-installer 2>/dev/null | grep "msttcorefonts/accepted-mscorefonts-eula: true"`;
	if [ "${COREFONTS}" = "" ]; then
		zenity --warning --title="${SERVICE}" --text "${gettext_fonts_still_needed}";
		exit;
	fi
	gksudo -- apt-get install --yes --reinstall ttf-mscorefonts-installer;
fi

# Transition over old profiles (from before version 0.6.0)
if [ -f "${HOME}/.netflix-desktop/netflix-desktop.sha256sums" ]; then
	mv "${HOME}/.netflix-desktop" "${WINE_BROWSER}";
	mv "${WINE_BROWSER}/drive_c/netflix-profile" "${WINE_BROWSER}/drive_c/browser-profile";
	mv "${WINE_BROWSER}/netflix-desktop.sha256sums" "${LOCAL_SUMS}";
	cp -a "${INSTDIR}/browser-profile/extensions" "${WINE_BROWSER}/drive_c/browser-profile/";
fi

# Copy over the specially configured user profile if installation has never been performed previously
if [ ! -f "${LOCAL_SUMS}" ]; then
	mkdir -p "${WINE_BROWSER}/drive_c";
	cp -a "${INSTDIR}/browser-profile" "${WINE_BROWSER}/drive_c/browser-profile";
fi

export WINEPREFIX="${WINE_BROWSER}";
CLIENT_SIDE_GRAPHICS_WORKAROUND=0;
if [ "$(cmp "${LOCAL_SUMS}" "${GLOBAL_SUMS}" > /dev/null; echo $?)" -ne "0" ]; then
	# If no previous installation has been performed (or new installation packages are available) then install the software we need to the local prefix
	UPGRADE=0;
	TASK="local installation";
	if [ -f "${LOCAL_SUMS}" ]; then
		UPGRADE=1;
		TASK="profile upgrade";
	fi
	(
		echo "1";
		${WINE} wineboot > /dev/null;
		${WINE} "${INSTDIR}/FirefoxSetup.exe" /INI=Z:\\usr\\share\\wine-browser-installer\\browser-settings.ini > /dev/null;
		${WINE} "${INSTDIR}/SilverlightSetup.exe" /q /doNotRequireDRMPrompt /noupdate > /dev/null;
		echo "100";
	) | zenity --progress --pulsate --no-cancel --auto-close --text="Performing ${TASK}...";
	# If not upgrading then make sure the installer fully finishes
	if [ "${UPGRADE}" -eq "0" ]; then
		until [ -f "${HOME}/.local/share/applications/wine/Programs/Microsoft Silverlight/Microsoft Silverlight.desktop" ]; do
			sleep 0.1;
		done;
	fi
	# Remove the Silverlight menu shortcut
	rm "${WINE_BROWSER}/drive_c/users/ehoover/Start Menu/Programs/Microsoft Silverlight/Microsoft Silverlight.lnk";
	rm "${HOME}/.local/share/applications/wine/Programs/Microsoft Silverlight/Microsoft Silverlight.desktop";
	xdg-desktop-menu uninstall "${HOME}/.local/share/applications/wine/Programs/Microsoft Silverlight/Microsoft Silverlight.desktop";
	# Install the hash file (indicates whether updates are necessary)
	cp "${GLOBAL_SUMS}" "${LOCAL_SUMS}";
else
	# If a previous installation exists then confirm that the profile is up-to-date
	EXTENSION_INSTALLED=0;
	if [ -f "${WINE_BROWSER}/profile-settings" ]; then
		. "${WINE_BROWSER}/profile-settings";
	fi
	WINEVERSION=`/opt/wine-compholio/bin/wine --version | sed -e 's/wine-//'`;
	OLDVERSION=`cat "${WINE_BROWSER}/wine-version" 2> /dev/null`;
	NEWWINE=`vercomp "${WINEVERSION}" "1.5.19"`;
	OLDPROFILE=`vercomp "${OLDVERSION}" "1.5.19"`;
	# Wipe the DRM folder if we're upgrading to Wine 1.5.19 or newer (new extended attribute format)
	if [ "${NEWWINE}" -ge "0" ] && [ "${OLDPROFILE}" -lt "0" ]; then
		rm -Rf "${WINE_BROWSER}/drive_c/users/Public/Application Data/Microsoft/PlayReady/"*;
	fi
	# Install the new window closing extension
	if [ "${EXTENSION_INSTALLED}" -ne "1" ]; then
		cp -a "${INSTDIR}/browser-profile/extensions" "${WINE_BROWSER}/drive_c/browser-profile/";
	fi
fi
# Install the workaround for Wine Bug #31812
if [ "${CLIENT_SIDE_GRAPHICS_WORKAROUND}" -ne "1" ]; then
	tmpfile="/tmp/wine-browser.$$.reg";
	echo -e "REGEDIT4\n\n[HKEY_CURRENT_USER\\Software\\Wine\\X11 Driver]\n\"ClientSideGraphics\"=\"N\"\n" >${tmpfile};
	${WINE} regedit ${tmpfile};
	rm ${tmpfile};
fi
echo "${WINEVERSION}" > "${WINE_BROWSER}/wine-version";
echo "# Wine Browser profile settings (do not edit)
EXTENSION_INSTALLED=1;
CLIENT_SIDE_GRAPHICS_WORKAROUND=1;
" > "${WINE_BROWSER}/profile-settings";

# Setup our specially prepared profile
if [ "${RELAYLOG}" -eq "1" ]; then
	OUTPUT="${HOME}/wine-browser.log";
	rm "${OUTPUT}" 2>/dev/null;
	DBGTMP="";
	if [ "${WINEDEBUG}" != "" ]; then
		DBGTMP=",${WINEDEBUG}";
	fi
	export WINEDEBUG="+relay${DBGTMP}";
elif [ "${SHOWDEBUG}" -eq "1" ]; then
	OUTPUT="/dev/fd/2";
else
	OUTPUT="/dev/null";
fi
if [ "${SHOWDEBUG}" -eq "1" ]; then
	# The "--showdebug" flag does several things:
	# 1) It outputs additional driver information to the console to help find the source of OpenGL issues
	# 2) It enables verbose libgl debugging and outputs this information to the console
	# 3) It allows Wine debug messages to be written to the console
	echo "################################################################################" 1>>${OUTPUT};
	echo "# OpenGL Diagnostics                                                           #" 1>>${OUTPUT};
	echo "################################################################################" 1>>${OUTPUT};
	glxinfo | grep -e 'direct rendering:' -e 'server glx vendor string:' -e 'server glx version string:' 1>>${OUTPUT};
	echo "################################################################################" 1>>${OUTPUT};
	echo "# Firefox                                                                      #" 1>>${OUTPUT};
	echo "################################################################################" 1>>${OUTPUT};
	export LIBGL_DEBUG="verbose";
fi
# Launch Firefox with our special profile
${WINE} "C:\\Program Files\\Mozilla Firefox\\firefox.exe" -profile "C:\\browser-profile" "${URL}" 2>>${OUTPUT};
