#!/bin/dash

# Enable translation capabilities
. gettext.sh
export TEXTDOMAIN="netflix-desktop";
export TEXTDOMAINDIR="/usr/share/locale";

# Overridable environment variables
if [ "${PACKAGE}" = "" ]; then
	PACKAGE="wine-browser-installer";
fi
if [ "${WINEPREFIX}" = "" ]; then
	WINEPREFIX="${HOME}/.wine-browser";
fi
if [ "${URL}" = "" ]; then
	URL="http://www.compholio.com/wine-browser/";
fi
if [ "${SERVICE}" = "" ]; then
	SERVICE=$(gettext "On Demand Wine Browser");
fi
export WINEPREFIX;

# Static environment variables (or based on variables from above)
INSTDIR="/var/lib/wine-browser-installer";
PKG_DIR="/usr/share/wine-browser-installer";
OTHER_SUMS="${PKG_DIR}/${PACKAGE}.sha256sums";
LOCAL_SUMS="${WINEPREFIX}/wine-browser.sha256sums";
GLOBAL_SUMS="${PKG_DIR}/wine-browser-installer.sha256sums";
BROWSER_PROFILE="${WINEPREFIX}/drive_c/browser-profile";
WINE="/opt/wine-compholio/bin/wine";
SHOWDEBUG="0";
RELAYLOG="0";
ALLOW_ADDONS="0";
SUDO=$(which gksudo 2>/dev/null);
if [ "${SUDO}" = "" ]; then
	SUDO=$(which kdesudo 2>/dev/null);
fi
if [ "${SUDO}" = "" ]; then
	SUDO=$(which beesu 2>/dev/null);
fi
# If the patched Wine is unavailable then use the system installed version
test -x "${WINE}" || WINE=$(which wine);

# 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 not available, please enable compositing support and relaunch \$SERVICE.");

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

# Install a Firefox setting
conf_ff_setting () {
	PREF_KEY="$1";
	PREF_VALUE="$2";
	PREFERENCES=$(cat "${BROWSER_PROFILE}/prefs.js");
	HAS_KEY=$(echo "${PREFERENCES}" | grep -c "${PREF_KEY}");
	if [ "${HAS_KEY}" -eq "0" ]; then
		PREFERENCES=$(echo "${PREFERENCES}"; echo "user_pref(\"${PREF_KEY}\", \"placeholder\");");
	fi
	PREFERENCES=$(echo "${PREFERENCES}" | sed 's|\(user_pref("'"${PREF_KEY}"'", \)[^)]*\();\)|\1'"${PREF_VALUE}"'\2|');
	echo "${PREFERENCES}" > "${BROWSER_PROFILE}/prefs.js";
}

# Process any command-line arguments
for arg in "$@"; do
	case "$arg" in
		--showdebug)
			SHOWDEBUG="1";
			;;
		--relaylog)
			SHOWDEBUG="1";
			RELAYLOG="1";
			;;
		--allowaddons)
			ALLOW_ADDONS="1";
			;;
		*)
			eval_gettext "Unrecognized command-line argument '\$arg', usage:"; echo;
			progname=`basename $0`;
			echo -n "$progname "; gettext "[options]"; echo;
			echo;
			gettext "Options:"; echo;
			printf "\t--showdebug\t"; gettext "Show Wine debug output."; echo;
			printf "\t--relaylog\t"; gettext "Collect a Wine '+relay' log."; echo;
			printf "\t--allowaddons\t"; gettext "Allow Wine Gecko and Wine Mono within the prefix."; echo;
			exit;
			;;
	esac;
done

# 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 (graphical sudo takes forever to exit each time)
		${SUDO} "${PKG_DIR}/download-missing-files" ${PACKAGE} "${SERVICE}";
	fi
done

# Make sure the prefix folder exists before testing its attributes
if [ ! -d "${WINEPREFIX}" ]; then 
	mkdir "${WINEPREFIX}";
fi

# Make sure that the filesystem supports extended file attributes
"${PKG_DIR}/test-xattr" "${WINEPREFIX}";
XATTR="$?";
if [ "${XATTR}" -ne "0" ]; then
	if [ "${XATTR}" -eq "1" ]; then
		MESSAGE=$(eval_gettext "Unable to test extended attributes at location '\${WINEPREFIX}'.");
	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 available
GLX_EXT=$(glxinfo | grep GLX_EXT_texture_from_pixmap);
if [ -z "${GLX_EXT}" ]; then
	zenity --warning --title="${SERVICE}" --text "${gettext_compositing_error}";
	exit;
fi

# Make sure that the MS core true type fonts are installed
COREFONTS=$(fc-list | grep "msttcore");
if [ "${COREFONTS}" = "" ]; then
	# if fontconfig is unavailable then see if debconf can find it
	COREFONTS=$(debconf-show ttf-mscorefonts-installer 2>/dev/null | grep "msttcorefonts/accepted-mscorefonts-eula: true");
fi
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
	${SUDO} ${PKG_DIR}/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
	${SUDO} -- 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" "${WINEPREFIX}";
	mv "${WINEPREFIX}/drive_c/netflix-profile" "${BROWSER_PROFILE}";
	mv "${WINEPREFIX}/netflix-desktop.sha256sums" "${LOCAL_SUMS}";
	cp -a "${PKG_DIR}/browser-profile/extensions" "${BROWSER_PROFILE}/";
fi

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

# Disable installing Mono and Gecko
if [ "${ALLOW_ADDONS}" -eq "1" ]; then
	export WINEDLLOVERRIDES="mscoree,mshtml=";
fi

# Some portions of this script depend on the Wine version
WINEVERSION=$(${WINE} --version | sed -e 's/wine-//');

CLIENT_SIDE_GRAPHICS_WORKAROUND=0;
BROWSER_USER_AGENT_WORKAROUND=0;
BROWSER_KATSOMO_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=$(gettext "Performing local installation...");
	if [ -f "${LOCAL_SUMS}" ]; then
		UPGRADE=1;
		TASK=$(gettext "Performing 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="${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 "${WINEPREFIX}/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 "${WINEPREFIX}/profile-settings" ]; then
		. "${WINEPREFIX}/profile-settings";
	fi
	OLDVERSION=`cat "${WINEPREFIX}/wine-version" 2> /dev/null`;
	NEWWINE=`vercomp "1.5.19" "${WINEVERSION}"`;
	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}" -ge "0" ]; then
		rm -Rf "${WINEPREFIX}/drive_c/users/Public/Application Data/Microsoft/PlayReady/"*;
	fi
	# Install the new window closing extension
	if [ "${EXTENSION_INSTALLED}" -ne "1" ]; then
		cp -a "${PKG_DIR}/browser-profile/extensions" "${BROWSER_PROFILE}/";
	fi
fi
# Install the workaround for Wine Bug #31812
NEWWINE=$(vercomp "1.6" "${WINEVERSION}");
if [ "${CLIENT_SIDE_GRAPHICS_WORKAROUND}" -ne "1" ] && [ "${NEWWINE}" -lt "0" ]; then
	# Disable client side graphics (Wine < 1.6)
	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};
	CLIENT_SIDE_GRAPHICS_WORKAROUND=1;
elif [ "${CLIENT_SIDE_GRAPHICS_WORKAROUND}" -ne "0" ] && [ "${NEWWINE}" -ge "0" ]; then
	# Enable client side graphics (Wine >= 1.6)
	tmpfile="/tmp/wine-browser.$$.reg";
	echo -e "REGEDIT4\n\n[HKEY_CURRENT_USER\\Software\\Wine\\X11 Driver]\n\"ClientSideGraphics\"=\"Y\"\n" >${tmpfile};
	${WINE} regedit ${tmpfile};
	rm ${tmpfile};
	CLIENT_SIDE_GRAPHICS_WORKAROUND=0;
fi
# Install the workaround for Netflix expecting a specific Firefox version (without requiring a Silverlight upgrade)
if [ "${BROWSER_USER_AGENT_WORKAROUND}" -ne "1" ]; then
	conf_ff_setting "general.useragent.override" "\"Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0\"";
fi
# Install the workaround for Katsomo locking up on exit
if [ "${BROWSER_KATSOMO_WORKAROUND}" -ne "1" ]; then
	conf_ff_setting "dom.ipc.plugins.processLaunchTimeoutSecs" "1";
	conf_ff_setting "dom.ipc.plugins.timeoutSecs" "2";
fi
echo "${WINEVERSION}" > "${WINEPREFIX}/wine-version";
echo "# Wine Browser profile settings (do not edit)
EXTENSION_INSTALLED=1;
CLIENT_SIDE_GRAPHICS_WORKAROUND=${CLIENT_SIDE_GRAPHICS_WORKAROUND};
BROWSER_USER_AGENT_WORKAROUND=1;
BROWSER_KATSOMO_WORKAROUND=1;
" > "${WINEPREFIX}/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=`glxinfo`;
	DRENDER=`echo "${GLXINFO}" | grep 'direct rendering:' | sed 's/[^:]*: //'`;
	GLVENDOR=`echo "${GLXINFO}" | grep 'server glx vendor string:' | sed 's/[^:]*: //'`;
	GLVER=`echo "${GLXINFO}" | grep 'server glx version string:' | sed 's/[^:]*: //'`;
	echo "Direct Rendering: ${DRENDER}" 1>>${OUTPUT};
	echo "OpenGL Vendor: ${GLVENDOR}" 1>>${OUTPUT};
	echo "GLX Version: ${GLVER}" 1>>${OUTPUT};
	DRIVERVER="";
	if [ "${GLVENDOR}" = "NVIDIA Corporation" ]; then
		DRIVERVER=`nvidia-settings --version | grep version | sed 's/.*version \([^ ]*\) .*/\1/'`;
	fi
	if [ "${DRIVERVER}" != "" ]; then
		echo "Driver Version: ${DRIVERVER}";
	fi
	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} &
PID=$!;
# Suspend the screensaver and suspend operations for the user while Firefox is running
while $(kill -s 0 ${PID} 2>/dev/null); do
	dbus-send --session --dest=org.gnome.ScreenSaver --type=method_call /org/gnome/ScreenSaver org.gnome.ScreenSaver.SimulateUserActivity;
	sleep 30;
done
