#!/bin/sh

# Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Running Chromium via this script makes it possible to set Chromium as the
# default browser directly out of a compile, without needing to package it.

DESKTOP="chromium-devel"
TITLE="Chromium"

# Check to see if there is a desktop file of the given name
exists_desktop_file() {
    # Build a search list from $XDG_DATA_HOME and $XDG_DATA_DIRS, the latter
    # of which can itself be a colon-separated list of directories to search.
    search="${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
    IFS=:
    for dir in $search; do
        unset IFS
        [ "$dir" -a -d "$dir/applications" ] || continue
        [ -r "$dir/applications/$DESKTOP.desktop" ] && return
    done
    # Didn't find it in the search path
    return 1
}

# Generate a desktop file that will run this script
generate_desktop_file() {
    apps="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
    mkdir -p "$apps"
    cat > "$apps/$DESKTOP.desktop" << EOF
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Name=$TITLE
Exec=$CHROME_WRAPPER %U
Terminal=false
Icon=$HERE/product_logo_48.png
Type=Application
Categories=Application;Network;WebBrowser;
MimeType=text/html;text/xml;application/xhtml_xml;
EOF
}

# Let the wrapped binary know that it has been run through the wrapper
export CHROME_WRAPPER="`readlink -f "$0"`"
export CHROME_DESKTOP="$DESKTOP.desktop"

HERE="`dirname "$CHROME_WRAPPER"`"

case ":$PATH:" in
  *:$HERE:*)
    # $PATH already contains $HERE
    ;;
  *)
    # Append $HERE to $PATH
    export PATH="$PATH:$HERE"
    ;;
esac

# Always use our ffmpeg and other shared libs.
export LD_LIBRARY_PATH="$HERE:$HERE/lib:$HERE/lib.target:$LD_LIBRARY_PATH"

export GDK_PIXBUF_MODULE_FILE="$HERE/etc/gtk-2.0/gdk-pixbuf.loaders"
export GTK_SYSCONFDIR="$HERE/etc/gtk-2.0"
export FONTCONFIG_PATH="$HERE/etc/fonts"
export FC_CONFIG_DIR="$HERE/etc/fonts"
export PANGO_RC_FILE="$HERE/pangorc"
if [ -e "/bham" ]
then
	export CUPS_SERVER="printhost.cs.bham.ac.uk"
fi

# Put cache in temporary location to save profile space
export XDG_CACHE_HOME="/tmp/chromium-${USER}"
export CCACHE_DIR="/tmp/chromium-${USER}"

exists_desktop_file || generate_desktop_file

cd $HERE

# Update user list
USER_FILE=/bham/ums/linux/pd/packages/chrome/users.txt
touch $USER_FILE
CURRENT_USER_LINE=$( grep `whoami` $USER_FILE )
if [ "$CURRENT_USER_LINE" == "" ]
then
	CURRENT_USER_LINE="`whoami` 1"
	echo "$CURRENT_USER_LINE" >> $USER_FILE
else
	CURRENT_USER_COUNT=`expr match "$CURRENT_USER_LINE" '.*\s\([0-9]*\)'`
	CURRENT_USER_COUNT=$((CURRENT_USER_COUNT + 1))
	PREVIOUS_USER_LINE=$CURRENT_USER_LINE
	CURRENT_USER_LINE="`whoami` $CURRENT_USER_COUNT"
	sed -i "s/$PREVIOUS_USER_LINE/$CURRENT_USER_LINE/g" $USER_FILE
fi
# End user list update

exec "$HERE/chrome" "$@"
