#!/bin/bash
_package="smart-notebook"
_version="10.2.559.1-1"
_function="post"
_install_dir="Notebook Software"
_install_prefix="/opt/SMART Technologies"
export INSTALL_DIR="$_install_prefix"/"$_install_dir"


##AUTOPACKAGE_IMPORT_BEGIN##
##############################################
# Inserted: autopackage specific script

function all_action ()
{



##########################################################################################################

if [[ -n "${SHORTNAME:-""}" ]] && [[ -f "/tmp/debug_${SHORTNAME}" ]]; then set -x; fi
if [[ -n "${_package:-""}" ]] && [[ -f "/tmp/debug_${_package}" ]]; then set -x; fi

export SMARTTECHCONFNAME="/etc/xdg/SMART Technologies.conf"
export OLD_SMARTTECHCONFNAME="/etc/xdg/smarttech.conf"
export LANGUAGE_SETUP_CONFIG="/etc/xdg/SMART Technologies/Language Setup.conf"
export NOTEBOOK_CONFIG="/etc/xdg/SMART Technologies/SMART Notebook.conf"
export PREFIX="/opt/SMART Technologies"
export INSTALL_DIR="${PREFIX}/Notebook Software"

export _store_dir="${PREFIX}/.store/SMARTNotebookSoftware"

##########################################################################################################

########################################################################
# Substituted: debian marker

export SOFTWAREVERSION="10.2.559.1"
export package_name="smart-notebook"
export autopackage_short_name="SMARTNotebookSoftware"
export debian_script="true"
export _store_dir="${PREFIX}/.store/${package_name}"
export _install_log_file="${_store_dir}/install/installlog"
export _install_log_file2="${_store_dir}/install/installlog2"
export _install_log_file3="${_store_dir}/install/installlog3"
export NO_GUI="1"

##CUSTOMIZATION_START##
##CUSTOMIZATION_END##

# /Substituted
########################################################################

########################################################################
# Substituted: autopackage port
# Rewritten or copied subset of autopackage support code.
# www.autopackage.org

function removeLine()
{
	local file="$1"
	local line="$2"
	local temp=$( /bin/mktemp -p /tmp )
	cat "$file" | /bin/egrep -v "^${line}\$" || true > "$temp"
	mv "$temp" "$file"
}

function dirIsEmpty()
{
	local dir="$1"
	if [[ ! -d "$dir" ]]
	then
		return 0
	fi

	if [[ "$(ls "$dir")" == "" ]]
	then
		return 0
	else
		return 1
	fi
}

function compareVersionsSimple()
{
    trace comparing required $1 to current $2
	local index=0
	local max
# replace all '.' with whitespace to index for arrays and remove '-' '_' '/' '+'
	local x=${1//./ }; x=${x//-/}; x=${x//_/}; x=${x//\//}; x=${x//+/}
	local y=${2//./ }; y=${y//-/}; y=${y//_/}; y=${y//\//}; y=${y//+/}
	x=(`echo $x`)
	y=(`echo $y`)
	let "cntx=${#x[@]}"
	let "cnty=${#y[@]}"
	if [ $cntx -gt $cnty ]; then
		max="$cntx"
	else
		max="$cnty"
	fi

	while [[ "$index" -lt "$max" ]]
	do
# special case: catches wildcard in decimal group and returns PASS
		if [ `expr length "${x[$index]}"` = 1 ] && [[ `expr index "${x[$index]}" 'x'` -eq "1" ]]; then return 0; fi
		if [[ "${x[$index]}" != "" ]] && [[ "${y[$index]}" = "" ]]; then return 1; fi
		if [[ "${x[$index]}" < "${y[$index]}" ]]; then return 0; fi
		if [[ "${x[$index]}" > "${y[$index]}" ]]; then return 1; fi
		let "index = $index + 1"
	done
	return 0;
}

function compareVersions()
{
	compareVersionsSimple "$1" "$2"
	return $?
}

function endsWithNewline()
{
    local end=`tail --bytes=1 "$1"`
    test "$end" == "`echo`"
    return $?
}

function addLine()
{
    trace called with $1, $2
    local file="$1"
    local line="$2"

    [ ! -e "$file" ] && touch "$file" || true
    if ! endsWithNewline "$file"; then
        echo >> "$file"
    fi
    echo "$line" >> "$file"
}

function MakeInstallFile()
{
	local name="$1"; shift
	local dir="${PREFIX}/.store/${package_name}/install"
	local file="$dir/$name"

	if [[ ! -d "${dir}" ]]
	then
		mkdirs "${dir}" > /dev/null
	fi
	/bin/touch "${file}" > /dev/null
	logFile "${file}"

	echo "${file}"
}

function _updateBashEnv()
{
	local pathFile="$1"
	local bashPathFile
	local files
	declare -a files

	local IFS=

	files=("/etc/profile")
	if [[ -f /etc/bash.bashrc ]]; then
	    files[${#files[@]}]="/etc/bash.bashrc"
	else
	    files[${#files[@]}]="/etc/bashrc"
	fi
	bashPathFile="$( MakeInstallFile "bash-path" )"

##### BEGIN HEADER
	cat <<EOF > "$bashPathFile"
# Auto-generated file. DO NOT EDIT
if [[ "x\$BASH" == "x" ]]; then
# Do not run in zsh or other shells
	return
fi

function __autopackage_addBashPath
{
	local name=\$1
	local path=\$2
	local append=\$3
	local kind
	local tmp
	local array
	declare -a array

	local IFS=':'
	array=(\${!name});
	for DIR in "\${array[@]}"; do
		if [[ "\$DIR" = "\$path" ]]; then
			return 0
		fi
	done

	if [[ "\${!name}" = "" ]]; then
		eval "export \$name=\"\$path\""
	elif \$append; then
		eval "export \$name=\\"\$path:\\\$\$name\""
	else
		eval "export \$name=\\"\\\$\$name:\$path\""
	fi
	return 0
}

EOF
##### END HEADER

	IFS=$'\n'
	while read LINE; do
		kind="${LINE:0:1}"
		tmp="${LINE:2}"
		name=`echo "$tmp" | sed 's/	.*//'`
		path=`echo "$tmp" | sed 's/.*	//'`

		if [[ "$kind" = "#" ]]; then
			continue
		elif [[ "$kind" = "A" ]]; then
# Append
			echo "__autopackage_addBashPath \"$name\" `escapeFilename \"$path\"` true" >> "$bashPathFile"
		elif [[ "$kind" = "P" ]]; then
# Prepend
			echo "__autopackage_addBashPath \"$name\" `escapeFilename \"$path\"` false" >> "$bashPathFile"
		fi
	done < "$pathFile"

# Make sure the file is included in the bash startup scrips
	IFS=
	for F in "${files[@]}"; do
		path=`escapeValue "[[ -f \"$bashPathFile\" ]] && . \"$bashPathFile\""`
		if [[ -f "$F" ]] && ! grep "^$path$" "$F" &>/dev/null; then
			addLine "$F" "[[ -f \"$bashPathFile\" ]] && . \"$bashPathFile\""
		fi
	done
}

function warn()
{
	echo "$@" >&2
	return 0
}

function escapeValue()
{
    echo "$1" | sed -e 's/\//\\\//g; s/\./\\./g; s/\*/\\*/g; s/\[/\\[/g; s/\]/\\]/g' -
}

function updateEnv()
{
	pushOptE; set +e;

# updateEnv saves changes to /etc/autopackage/paths (or ~/.config/autopackage/paths),
# instead of writing to bashrc as it used to. A bash script, bash-paths, is created
# from that file. bashrc is then modified to 'source' that file. This minimizes the
# chance of screwing up bashrc (not that I've ever seen it happening, but some people
# are overly paranoid) and makes it easier to support new shells.

	local append=false
	local check=true

# Parse arguments
	while [[ ${1:0:2} == "--" ]]; do
		if [[ "$1" == "--append" ]]; then
			append=true;
		elif [[ "$1" == "--check" ]]; then
			check=true;
		else
			warn unknown parameter $1;
		fi
		shift
	done

	local name="$1"
	local dest="$2"
	local val=${!name}
	local oIFS="$IFS"
	local array
	local line
	local tmp
	local apkg_path_file
	declare -a array
	declare -a files

# Check whether the path is already in the variable
	local alreadyInVariable=0
	if $check; then
		IFS=':';
		array=($val);
		for DIR in "${array[@]}"; do
			if [[ "$DIR" == "$dest" ]]; then
				trace $dest is already in $name
				alreadyInVariable=1
				break
			fi
		done
		IFS="$oIFS"
	fi

# Save this path into our own special path file
	apkg_path_file="$( MakeInstallFile "path" )"

	if $append; then
		line="A	$name	$dest"
	else
		line="P	$name	$dest"
	fi

	local alreadyInFile=0
	if [[ -f "$apkg_path_file" ]]; then
# Check whether this line is already in the path file
		tmp=`escapeValue "$line"`
		if grep "^$tmp$" "$apkg_path_file" &>/dev/null; then
			trace $dest already in path file
			alreadyInFile=1
		fi
	else
# Create the header of the path file if file doesn't exist
		tmp=`dirname "$apkg_path_file"`
		if [[ ! -d "$tmp" ]]; then
			mkdirs "$tmp"
		fi

		echo '# Auto-generated file; DO NOT EDIT!!!' > "$apkg_path_file"
	fi

	if [[ $alreadyInFile = 0 ]]; then
		echo "$line" >> "$apkg_path_file"
	fi
	trace $dest added to $apkg_path_file
	if [[ "$alreadyInVariable" == "0" ]]; then
		if [[ "${!name}" = "" ]]; then
			eval "export $name=\"$dest\""
		elif $append; then
			eval "export $name=\"$dest:\$$name\""
		else
			eval "export $name=\"\$$name:$dest\""
		fi
	fi

# The path file is not a shell script. Generate
# shell scripts from the path files.
	_updateBashEnv "$apkg_path_file"

# Finally, add an uninstall log
	logCommand "if dirIsEmpty `escapeFilename \"$dest\"`; then removeLine \"$apkg_path_file\" \"$line\"; _updateBashEnv \"$apkg_path_file\"; fi;"

	popOptE
	return 0
}

function isInList()
{
	local oIFS=$IFS

	if [[ ${1:0:2} == "-F" ]]; then
		IFS=${1:2:3}
		shift
	else
		IFS=:
	fi

	if [[ ${#@} != 2 ]]; then
		err not enough arguments given
		IFS=$oIFS
		return 1
	fi

	for i in $2; do
		if [[ "$i" == "$1" ]]; then
			IFS="$oIFS";
			return 0;
		fi
	done

	IFS=$oIFS
	return 1
}

function getMajor()
{
    echo "${1%%.*}"
}

function getLanguages()
{
    local language_list language_match_list language_item language_element

# order and structure defined by The Open Group Base Specifications Issue 6
# use LANGUAGE if it exist because it is used by GNU gettext
	if [[ "$LANGUAGE" != "" && "$LANGUAGE" != "C" ]]; then
		language_list="$LANGUAGE"
		trace using LANGUAGE=$LANGUAGE
# LC_ALL is used to default LC_* environment variables
	elif [[ "$LC_ALL" != "" && "$LC_ALL" != "C" ]]; then
		language_list="$LC_ALL"
		trace using LC_ALL=$LC_ALL
# use LANG if LC_ALL is not present
	elif [[ "$LANG" != "" && "$LANG" != "C" ]]; then
		language_list="$LANG"
		trace using LANG=$LANG
# define default language
	else
		language_list="en"
		trace using default as language_list=$language_list
	fi

# filter for LANGUAGE information syntax and strip encoding descriptions
    language_list_temp=`echo "$language_list" | sed 's/:/ /g'`
    unset language_list
    for language_item in $language_list_temp; do
# strip encoding
        language_item=`getMajor "$language_item"`
        if ! isInList '-F ' "$language_item" "$language_list"; then
            if [[ "$language_list" == "" ]]; then
                language_list=`echo "$language_item"`
            else
                 language_list=`echo "$language_list $language_item"`
            fi
        fi
        unset language_item language_match
    done

# breakdown language_COUNTRY by stripping COUNTRY description and add to language_match_list
    for language_item in $language_list; do
        language_element="${language_item/_*/}"
        if [[ "$language_item" != "$language_element" ]]; then
            language_match_list=`echo "$language_match_list $language_element"`
        fi
        unset language_item language_element
    done

# cycle through language_match_list and add to language_list if it does not exist in language_list
    for language_match_item in $language_match_list; do
        unset language_match
        if ! isInList '-F ' "$language_match_item" "$language_list"; then
            language_list=`echo "$language_list $language_match_item"`
        fi
    done

# add default language 'en' if not present or derived
    if ! isInList '-F ' "en" "$language_list"; then
        trace adding en as default to language_list
        language_list=`echo "$language_list en"`
    fi

    trace language_list=$language_list
    echo "$language_list"
    return 0
}

# noop
function trace()
{
	return 0
}

function err()
{
	echo "$@" >&2
	return 0
}

function installIcon()
{
# updating icon cache, icons installed by deb already
	local paths=( "/usr/share/icons" "/usr/share/pixmaps" )

	if locateCommand gtk-update-icon-cache; then
		for D in "${paths[@]}"; do
			# check for theme cache file - if not present use --ignore-theme-index
			if [ -f "$D/hicolor/index.theme" ]; then
				trace running gtk-update-icon-cache with theme index $D/hicolor
				gtk-update-icon-cache --quiet "$D/hicolor" &>/dev/null
			else
				trace running gtk-update-icon-cache without theme index "$D/hicolor"
				gtk-update-icon-cache --quiet --ignore-theme-index "$D/hicolor" &>/dev/null
			fi
		done
	fi

	return 0
}

# noop
function installDesktop()
{
	return 0
}

function outputStatus()
{
	echo "$@"
}

function escapeFilename()
{
    echo "$1" | sed 's/\\/\\\\/g; s/"/\\"/g; s/ /\\ /g; s/\$/\\\$/g; s/(/\\(/g; s/)/\\)/g' | sed "s/'/\\\'/g"
}

function removeFile()
{
	local file="$1"; shift

	local dir="$(dirname "$file")"

	rm -f "$file" >/dev/null
	removeDir "$dir"
}

function removeDir()
{
	local location="$1"; shift

	# find the first existing directory
	while [[ ! -d "$location" ]]
	do
		location="$(dirname "$location")"
		if [[ "$location" == "/" ]]
 		then
			return 0
		fi
	done
	location="$(cd "$location" && pwd)"
	while rmdir "$location" > /dev/null 2>&1
	do
			location="$(dirname "$location")"
			if [[ "$location" == "/" ]]
			then
					return 0
			fi
	done
#	 rmdir -p "$location" > /dev/null 2>&1 || true
	return 0
}

function logCommand()
{
	if [[ ! -f "${_install_log_file}" ]]
	then
		mkdir -p "$( dirname "${_install_log_file}" )"
		touch "${_install_log_file}"
	fi

	echo "$@" >> "${_install_log_file}"
}

function logCommand2()
{
	if [[ ! -f "${_install_log_file2}" ]]
	then
		mkdir -p "$( dirname "${_install_log_file2}" )"
		touch "${_install_log_file2}"
	fi

	echo "$@" >> "${_install_log_file2}"
}

function logCommand3()
{
	if [[ ! -f "${_install_log_file3}" ]]
	then
		mkdir -p "$( dirname "${_install_log_file3}" )"
		touch "${_install_log_file3}"
	fi

	echo "$@" >> "${_install_log_file3}"
}

function logFile()
{
	local file="$1"; shift
	local dir="$(dirname "$file")"

	logCommand2 removeFile "$(escapeFilename "${file}")"
	logCommand3 removeDir "$(escapeFilename "${dir}")"
}

# noop
function copyFiles()
{
	return 0
}

# noop
function copyFile()
{
	return 0
}

function uninstallFromLog()
{
	if [[ -f "${_install_log_file}" ]]
	then
		( source "${_install_log_file}" )||true
		removeFile "${_install_log_file}"||true
	fi

	pushOptE; set +e
	if [[ -f "${_install_log_file2}" ]]
	then
		( source "${_install_log_file2}" )
		removeFile "${_install_log_file2}"
	fi

	if [[ -f "${_install_log_file3}" ]]
	then
		( source "${_install_log_file3}" )
		removeFile "${_install_log_file3}"
	fi
	popOptE
}

function locateCommand()
{
	unset lc_array
	unset lc_location
	unset lc_output
	unset lc_command
	unset lc_ret
	local ret_location
	local ret_output
	local ret_run
	local temp

	# process option flags
	if [[ "$1" = "-o" ]]; then
		ret_output=1
		shift
	elif [[ "$1" = "-l" ]]; then
		ret_location=1
		shift
	elif [[ "$1" = "-r" ]]; then
		ret_run=1
		shift
	elif [[ "$1" = "--" ]]; then
		shift
	fi
	lc_command="$1"

	temp=`which "$lc_command" 2>/dev/null | sed "s|~|$HOME|"`
	if [ "$temp" ]; then
		lc_array="$temp"
		lc_location="$lc_array"

		trace which:lc_location=$lc_location
		if [[ $ret_run = 1 || $ret_output = 1 || "$2" != "" ]]; then
			shift
			lc_output=`"$lc_location" "$@"`
			lc_ret=$?
		fi

		[ "$ret_output" ] && echo "$lc_output"
		[ "$ret_location" ] && echo "$lc_location"
		return 0
	fi

	temp=`whereis -b "$lc_command" 2>&1 | sed 's/.*: *//'`
	if [ "$temp" ]; then
		local -a x
		x=( $temp )
		lc_array="${temp[@]}"

		index=0
		while [[ "$index" -lt "${#x[@]}" ]]
		do
			# We're only looking for executable ojects
			if [[ -x "${x[$index]}" ]] && [[ -f "${x[$index]}" ]]; then
				lc_location="${x[$index]}"

				if [[ "$2" != "" || $ret_output = 1 || $ret_run = 1 ]]; then
					shift
					lc_output=`"$lc_location" "$@"`
					lc_ret=$?

					trace whereis:lc_location=$lc_location
					[[ "$lc_ret" != "0" ]] && return 1
				fi
				[ "$ret_output" ] && echo "$lc_output"
				[ "$ret_location" ] && echo "$lc_location"
				return 0
			fi
			let "index = $index + 1"
		done
		return 1
	else
		unset lc_location
		return 1
	fi
}

function stripBlankLines()
{
	echo "$1" | awk 'NF > 0' -
}

function getSection()
{
	trace getting section $2 from $1

	sed -nf /dev/stdin "$1" <<EOF
/^[     ]*\[[   ]*${2}[     ]*\][   ]*$/! d
:x
n
s/^\([  ]*\[.*\][   ]*\)$//
tq
p
bx
:q
q
EOF
	return
}

function removeSectionLine()
{
	local filename="$1"
	local section="$2"
	local match="$3"
	local temp

	# test to find match - if found then do not echo the $match_line text
	local match_line=`getSection "$filename" "$section" | grep -e $match`
	#                                            don't quote this ^^^^^^

	# gather file and do not echo the $match_line text
		while read;
		do
			line=`echo "$REPLY"`
			if [ `expr index "$line" '['` -eq 1 ]; then
				section_name=`echo "$line" | sed 's/.*\[//g; s/\].*//g'`
			fi
			if [[ ! "$line" = "$match_line" ]] || [[ ! "$section_name" = "$section" ]]; then
				if [ "$temp" ]; then
					temp=`echo "$temp"; echo "$line"`
				else
					temp=`echo "$line"`
				fi
			fi
		done <"$filename"
		echo "$temp" > "$filename"
}

function addSectionLine()
{
	local filename="$1"
	local section="$2"
	local replace="$3"
	local match="$4"
	local match_line
	local temp

	trace filename=$filename, section=$section
	trace replace=$replace, match=$match

	# test to find match - if found then replace otherwise rewrite file and add text line
	[ ! -e "$1" ] && touch "$1" || true
	[ "$match" ] && match_line=`getSection "$filename" "$section" | grep -e $match` || true
	#                                                                      ^^^^^^^^ don't quote this - why not though?

	if [ "$match_line" ]; then
		replace=`echo "$replace" | sed 's|\/|\\\/|g; s|\"|\\\"|g; s|\;|\\\;|g'`
		safeSed "$filename" "s|^${match_line}$|${replace}|"
	else
		local section_text=`getSection "$filename" "$section"`

		# does this section of text exist
		if [ "$section_text" ]; then

			# gather sections to add text line at the end of section
			while read;
			do
				line=`echo "$REPLY"`
				if [ `expr index "$line" '['` -eq 1 ]; then
					section_name=`echo "$line" | sed 's/.*\[//g; s/\].*//g'`
					# this order is to format the text output
					if [ "$temp" ]; then
						temp=`echo "$temp"; echo "[$section_name]"`
					else
						temp=`echo "[$section_name]"`
					fi
					section_text=`getSection "$filename" "$section_name"`
					if [[ "$section" = "$section_name" ]]; then
						section_text=`echo "$section_text"; echo "$replace"`
					fi
					if [[ "$section" = "Desktop Entry" ]]; then
						section_text=`stripBlankLines "$section_text" | sort`
						temp=`echo "$temp"; echo "$section_text"; echo " "`
					else
						section_text=`stripBlankLines "$section_text"`
						temp=`echo "$temp"; echo "$section_text"; echo " "`
					fi
				fi
			done <"$filename"
			echo "$temp" > "$filename"

		# add section marker and item text to file
		else

			echo "[$section]" >> "$filename"
			echo "$replace" >> "$filename"

		fi

	fi
	return 0
}

function safeSed()
{
	sed -i "$2" "$1"
}

function pushOptE()
{
	local last=${#__opt_stack_e[@]}
	if [[ $- == *e* ]]; then
	__opt_stack_e[$last]="1"
	else
	__opt_stack_e[$last]="0"
	fi
}

function popOptE()
{
	if [[ ${__opt_stack_e[${#__opt_stack_e[@]}-1]} == "1" ]]; then
	set -e
	else
	set +e
	fi
	unset __opt_stack_e[${#__opt_stack_e[@]}-1]
}

function mkdirs()
{
	local dir="$1"

	mkdir -p "$dir"

	logCommand3 removeDir "$(escapeFilename "$(cd "${dir}" && pwd)")"
}

########################################################################

# noop -- shouldn't run random stuff as root
function ExecuteAfterInstall()
{
	return 0
}

# noop
function ClearDependencies()
{
	return 0;
}

# noop
function UninstallPackage()
{
	return 0;
}

# /Substituted
########################################################################

##########################################################################################################

function BytesToString()
{
	local bytes="$1"
	local gb=1073741824
	local mb=1048576
	local kb=1024
	local div=1
	local suffix=""

	if (( bytes > gb ))
	then
		div=$gb
		suffix="GB"
	elif (( bytes > mb ))
	then
		div=$mb
		suffix="MB"
	else
		div=$kb
		suffix="KB"
	fi
	echo "$(( bytes/div )).$(( (bytes - div*(bytes/div))/(div/100) )) $suffix"
}

function MakeAbsolutePath()
{
	local file="$1"

	if [[ "${file}" != "" ]]
	then
		if [[ -e "${file}" ]]
		then
			file="$(cd "$(dirname "${file}")" && pwd)/$(basename "${file}")"
		elif [[ "${file:0:1}" != "/" ]]; then
			file="$(pwd)/${file}"
		fi
	fi

	echo "${file}"
}

function CopySupportFile()
{
	local file1="$1"; shift
	local file2="$(MakeAbsolutePath "$1")"; shift

	if [[ "${debian_script:-"false"}" != "true" ]]
	then
		copyFile --silent "$file1" "$file2"
		return $?
	fi

	if [[ "${file1:0:1}" != "/" ]]
	then
		file1="${_store_dir}/${file1}"
	fi

	if [[ ! -f "$file1" ]]; then return 1; fi

	local target_dir="$(dirname "$file2")"

	if [[ ! -d "$target_dir" ]]; then mkdirs "$target_dir"; fi
	/bin/cp -f "$file1" "$file2"

	logFile "$file2"
}

##########################################################################################################

function CreateXmlForSPU()
{
	local base_name="$1"
	local url="\"${2:-"http://webservices.smarttech.com/products/updates/linux"}\""
	local version="\"${3:-"$SOFTWAREVERSION"}\""
	local xml_path="${PREFIX}/${4:-"Product Update"}/share"

	mkdirs "${xml_path}"

	{
		echo '<root Location="Client">'
		echo "<Product CurrentVersion=${version} RemoteVersionFileURL=${url} RemoteVersionFile=\"${base_name}.xml\" />"
		echo '</root>'
	} > "${xml_path}/${base_name}.xml"

	logFile "${xml_path}/${base_name}.xml"
}

##################################################################################################
# xdg

function PrepareXdgUtils()
{
	local XDG_UTILS_PATH="$1"
	export PATH="$XDG_UTILS_PATH:$PATH"
}

function PrepareDesktopFiles()
{
	if [[ "${debian_script:-"false"}" == "true" ]]
	then
		cd "${_store_dir}"
	fi

	local DESKTOPS_PATH="$1"
	local BINARY_PATH="$2"

	local ESCAPEDSTRING=$( echo "$BINARY_PATH" | /bin/sed 's/\\/\\\\/g' | /bin/sed 's/\//\\\//g' )

	/bin/sed -i '{s/\(^Exec=\)\"*\([^\"]*\)\"*/\1\"'"$ESCAPEDSTRING"'\/\2\"/; s/ %f\"/\" %f/}' "$DESKTOPS_PATH"/*.desktop
}

function InstallMimes()
{(
	if [[ "${debian_script:-"false"}" == "true" ]]
	then
		cd "${_store_dir}"
	fi

	local MIMES_DIR="$1"
	local APP_INSTALL_DIR="$2"

	mkdirs "${APP_INSTALL_DIR}/installdata/mime/."

	local xdgMimePath="$(locateCommand -l xdg-mime)"

	if [[ -z "${xdgMimePath}" ]]
	then
		echo "Can not find xdg utils"
		return 1
	fi

	pushd "${MIMES_DIR}" > /dev/null

	OLD_IFS="$IFS"
	IFS=$'\n'
	for mime in $(ls -1 *.xml)
	do
		"${xdgMimePath}" install "${mime}"

		# Leaving mimes behind
		# copyFile "${mime}" "${APP_INSTALL_DIR}/installdata/mime/${mime}"
		# logCommand "\"${xdgMimePath}\" uninstall \"${APP_INSTALL_DIR}/installdata/mime/${mime}\""
	done
	IFS="$OLD_IFS"

	popd > /dev/null
)}

function InstallDesktops()
{(
	if [[ "${debian_script:-"false"}" == "true" ]]
	then
		cd "${_store_dir}"
	fi

	local DESKTOP_DIR="$1"
	local INSTALL_DATA="$2"
	local DIRECTORY_FILE_1="$(MakeAbsolutePath "$3")"
	local DIRECTORY_FILE_2="$(MakeAbsolutePath "$4")"
	local DIRECTORY_FILE_3="$(MakeAbsolutePath "$5")"

	local xdgDesktopPath="$(locateCommand -l xdg-desktop-menu)"

	if [[ -z "${xdgDesktopPath}" ]]
	then
		echo "Can not find xdg utils"
		return 1
	fi

	mkdirs "${INSTALL_DATA}"
	INSTALL_DATA="$(MakeAbsolutePath "${INSTALL_DATA}")"

# xdg-desktop-menu doesn't support spaces in filenames. Seriously, WTF?
	pushd "${DESKTOP_DIR}" > /dev/null

	if [[ -n "${DIRECTORY_FILE_1}" ]]
	then
		if [[ ! -f "${DIRECTORY_FILE_1}" ]]; then echo "${DIRECTORY_FILE_1} not exists"; fi
		/bin/cp "${DIRECTORY_FILE_1}" "${INSTALL_DATA}/."
		CopySupportFile "${DIRECTORY_FILE_1}" "./$(basename "${DIRECTORY_FILE_1}")"
		DIRECTORY_FILE_1="$(basename "${DIRECTORY_FILE_1}")"
	fi
	if [[ -n "${DIRECTORY_FILE_2}" ]]
	then
		if [[ ! -f "${DIRECTORY_FILE_2}" ]]; then echo "${DIRECTORY_FILE_2} not exists"; fi
		/bin/cp "${DIRECTORY_FILE_2}" "${INSTALL_DATA}/."
		CopySupportFile "${DIRECTORY_FILE_2}" "./$(basename "${DIRECTORY_FILE_2}")"
		DIRECTORY_FILE_2="$(basename "${DIRECTORY_FILE_2}")"
	fi
	if [[ -n "${DIRECTORY_FILE_3}" ]]
	then
		if [[ ! -f "${DIRECTORY_FILE_3}" ]]; then echo "${DIRECTORY_FILE_3} not exists"; fi
		/bin/cp  "${DIRECTORY_FILE_3}" "${INSTALL_DATA}/."
		CopySupportFile "${DIRECTORY_FILE_3}" "./$(basename "${DIRECTORY_FILE_3}")"
		DIRECTORY_FILE_3="$(basename "${DIRECTORY_FILE_3}")"
	fi

	local gnome_global_dir="/usr/share/gnome/apps"
	local kde_global_dir="/usr/share/applnk"

	OLD_IFS="$IFS"
	IFS=$'\n'
	for desktop in $(ls -1 *.desktop)
	do
		{
			echo -en "install\00"
			echo -en "--noupdate\00"
			if [[ -n "${DIRECTORY_FILE_1}" ]]; then echo -en "${DIRECTORY_FILE_1}\00"; fi
			if [[ -n "${DIRECTORY_FILE_2}" ]]; then echo -en "${DIRECTORY_FILE_2}\00"; fi
			if [[ -n "${DIRECTORY_FILE_3}" ]]; then echo -en "${DIRECTORY_FILE_3}\00"; fi
			echo -en "${desktop}\00"
		}	| /usr/bin/xargs -0 "${xdgDesktopPath}"

		# Ubuntu 9.04, GNOME 2.26.1 ignores OnlyShowIn=Old;
		# Whatever, old distros won't get any menues.
		if [[ -f "${gnome_global_dir}/${desktop}" ]]; then rm "${gnome_global_dir}/${desktop}"; fi
		if [[ -f "${kde_global_dir}/${desktop}" ]]; then rm "${kde_global_dir}/${desktop}"; fi

		logCommand "cd \"${INSTALL_DATA}\" && { \
			echo -en \"uninstall\\00\"; \
			echo -en \"--noupdate\\00\"; \
			if [[ -n \"${DIRECTORY_FILE_1}\" ]]; then echo -en \"${DIRECTORY_FILE_1}\\00\"; fi; \
			if [[ -n \"${DIRECTORY_FILE_2}\" ]]; then echo -en \"${DIRECTORY_FILE_2}\\00\"; fi; \
			if [[ -n \"${DIRECTORY_FILE_3}\" ]]; then echo -en \"${DIRECTORY_FILE_3}\\00\"; fi; \
			echo -en \"${desktop}\\00\"; \
		} 	| /usr/bin/xargs -0 \"${xdgDesktopPath}\""

	done
	IFS="$OLD_IFS"

	popd > /dev/null
)}

function UpdateDesktops()
{
# This is the xdg part : it is standard
	local xdgDesktopPath="$(locateCommand -l xdg-desktop-menu)"
	"${xdgDesktopPath}" forceupdate

# This is the new python-gmenu part which appeared on Ubuntu 10.04 / gnome
	local _ret=0
	local _cmd=/usr/share/gnome-menus/update-gnome-menus-cache ; [[ -x $_cmd ]] || return $_ret

	local _ds=$(echo ${XDG_DATA_DIRS:-/usr/share} |tr ':' ' ')
	for _d in $_ds ; do   # find new cache files
		_f=$(  ls -1  $_d/applications/desktop*cache 2>/dev/null || true )  # we assume there are 0 or 1
		if [[ "$_f" != "" ]]; then
			$_cmd $(dirname $_f) > $_f
			(( _ret = _ret + $? )) || true
		fi
	done

	return $_ret
}

##########################################################################################################

function Execute()
{(
	local libraries="$1"; shift
	local binary="$1"; shift

	pushOptE; set +e
	export LD_LIBRARY_PATH="$libraries"

	{
		while [ $# -gt 0 ]
		do
			echo -en "$1\00"
			shift
		done
	} | /usr/bin/xargs -0 "$binary"
	popOptE

	return 0
)}

function ExecuteAndFail()
{(
	local libraries="$1"; shift
	local binary="$1"; shift

	export LD_LIBRARY_PATH="$libraries"

	{
		while [ $# -gt 0 ]
		do
			echo -en "$1\00"
			shift
		done
	} | /usr/bin/xargs -0 "$binary"

	return $?
)}

function SlaughterOnUninstall()
{
	local binary_dir="$1"

	logCommand "\
		if [[ -z \"\${BYPASS_KILLING_ON_UNINSTALL}\" ]]; \
		then \
			if processes=\"\$( \"\$(locateCommand -l ps)\" -e -o pid,command | \"\$(locateCommand -l sed)\" \"s/^ *//\" | \"\$(locateCommand -l grep)\" \"^[0-9]* ${binary_dir}\" )\" \
			&& [[ \"\$processes\" != \"\" ]]; \
			then \
				echo \"\$processes\" | \"\$(locateCommand -l cut)\" -f1 -d \" \" | \"\$(locateCommand -l xargs)\" \"\$(locateCommand -l kill)\"; \
			fi; \
		fi"
}

##########################################################################################################

function CheckGUI()
{
	if [[ ! -z "${NO_GUI}" ]]; then return 1; fi
	if [[ -z "${DISPLAY}" ]]; then return 1; fi
	return 0
}

function RunActivation()
{(
	set +e; set +u

	# HACK: AW package would run it too, but definitions won't be installed yet, so upgrade would fail.
	"${PREFIX}/Activation Wizard/bin/activationwizard" --r 1>/dev/null 2> /dev/null

	if [[ -n "${PRODUCT_KEY}" ]]
	then
		if ! CheckGUI; then mode="6"; else mode="4"; fi
		"${PREFIX}/Activation Wizard/bin/activationwizard" --m=$mode --pk="${PRODUCT_KEY}" --puid=notebook_10 --a --v=1 > /dev/null
	fi
	return 0
)}

function RunGallerySetup()
{
	if ! (
		set +e; set +u

		local gallery_setup="${PREFIX}/Gallery Setup/bin/GallerySetup"
		local essentials_config="${PREFIX}/Gallery Setup/share/SMARTEssentials.gallerycollection"

		if [[ -n "${TEAM_CONTENT_PATH}" ]]
		then
			"${gallery_setup}" -teamcontent -destination "${TEAM_CONTENT_PATH}" | grep -v "^Read error:"||true
		fi

		if [[ -n "${NETWORK_CONTENT}" ]]
		then
			if [[ -z "${CONTENT_TARGET_PATH}" ]]; then return 1; fi
			"${gallery_setup}" -register -remote -forcedest -destination "${CONTENT_TARGET_PATH}" -configuration "${essentials_config}" | grep -v "^Read error:"||true
			exit $?
		fi

		if [[ -n "${NETWORK_CONTENT}" ]] || [[ "x" == "x${ADMIN_CONTENT}${ARTS_CONTENT}${ENGLISH_CONTENT}${GEOGRAPHY_CONTENT}${HISTORY_CONTENT}${MATH_CONTENT}${PEOPLE_CONTENT}${SCIENCE_CONTENT}${SPECIAL_CONTENT}${SPORTS_CONTENT}" ]]; then return 0; fi

		{
			if ! CheckGUI
			then
				echo -en "--noui\00"
			fi

			echo -en "-guid\00gallery.smarttech.com\00"
			echo -en "-authorized\00"
			echo -en "-locale\00${SB_LANG:-en_CA}\00"
			echo -en "-installsome\00"

			if CheckGUI
			then
				echo -en "-ui\00"
			else
				echo -en "-verbose\00"
			fi

			if [[ -n "${CONTENT_SOURCE_PATH}" ]]
			then
				echo -en "-source\00${CONTENT_SOURCE_PATH}\00"
			elif [[ -z "${DISALLOW_DOWNLOAD}" ]]
			then
				echo -en "-allowdownload\00"
			fi

			if [[ -n "${CONTENT_TARGET_PATH}" ]]; then echo -en "-destination\00${CONTENT_TARGET_PATH}\00"; fi

			if [[ -n "${ADMIN_CONTENT}" ]]; then echo -en "-c\00administration\00"; fi
			if [[ -n "${ARTS_CONTENT}" ]]; then echo -en "-c\00arts\00"; fi
			if [[ -n "${ENGLISH_CONTENT}" ]]; then echo -en "-c\00english\00"; fi
			if [[ -n "${GEOGRAPHY_CONTENT}" ]]; then echo -en "-c\00geography\00"; fi
			if [[ -n "${HISTORY_CONTENT}" ]]; then echo -en "-c\00history\00"; fi
			if [[ -n "${MATH_CONTENT}" ]]; then echo -en "-c\00math\00"; fi
			if [[ -n "${PEOPLE_CONTENT}" ]]; then echo -en "-c\00people\00"; fi
			if [[ -n "${SCIENCE_CONTENT}" ]]; then echo -en "-c\00tech\00"; fi
			if [[ -n "${SPECIAL_CONTENT}" ]]; then echo -en "-c\00needs\00"; fi
			if [[ -n "${SPORTS_CONTENT}" ]]; then echo -en "-c\00sports\00"; fi
		} | /usr/bin/xargs -0 "${gallery_setup}" | grep -v "^Read error:"||true
		# Some weirdness with ubuntu X server and Qt

		exit $?; )
	then
		outputStatus "Gallery installation failed."
	fi
	return 0
}

##########################################################################################################

function addOrReplaceSectionLine()
{
# Will replace first match, not nessesarily in the correct section :)
	local FILENAME="$1"
	local SECTION="$2"
	local KEY="$3"
	local VALUE="$4"

	if getSection "${FILENAME}" "${SECTION}" | grep "${KEY}" > /dev/null
	then
		removeMatchingSectionKeys "${FILENAME}" "${SECTION}" "${KEY}"
	fi

	addSectionLine "${FILENAME}" "${SECTION}" "${KEY}=${VALUE}"
}

function removeMatchingSectionKeys()
{
# It is kinda slow, but it works :)

	local FILENAME="$1"
	local SECTION="$2"
	local MATCH="$3"

	if [[ ! -e "${FILENAME}" ]]; then return; fi

	pushOptE; set +e

# Reading in whole file
	SECTIONS="$( grep "^\[.*\]" "${FILENAME}" | sed 's/\[//;s/\]//;s/\(^.*$\)/\"\1\"/' )"
	declare -a SECTIONS_ARRAY
	eval "SECTIONS_ARRAY=(${SECTIONS})"

	local i=-1
	local FILE_CONTENT
	while (( i++, i < ${#SECTIONS_ARRAY[@]} ))
	do
		local SECTION_CONTENT=$( getSection "${FILENAME}" "${SECTIONS_ARRAY[$i]}" )

		if [[ "${SECTIONS_ARRAY[$i]}" == "${SECTION}" ]]
		then
			SECTION_CONTENT=$( echo "${SECTION_CONTENT}" | grep -v "${MATCH}"||true )
		fi

		FILE_CONTENT=$(
			if [[ -n "${FILE_CONTENT}" ]]; then echo "${FILE_CONTENT}"; fi
			if [[ -n "${SECTION_CONTENT}" ]]
			then
				echo "[${SECTIONS_ARRAY[$i]}]"
				echo "${SECTION_CONTENT}"
			fi
		)
	done

	popOptE

	echo "${FILE_CONTENT}" > "${FILENAME}"
}

function GetSectionKey()
{
	local file_name="$1"; shift
	local section="$1"; shift
	local key="$1"; shift

	if [[ ! -e "${file_name}" ]]; then return; fi

	key="$(echo "$key" | sed 's#\\#\\\\#')"

	local section_content="$(getSection "${file_name}" "${section}")"
	local line="$(echo "${section_content}" | grep -m 1 "${key}")"

	echo "${line#*=}"
}

function CreateRecordForLanguageSetup()
{
	local config="$1"; shift
	local product_id="$1"; shift
	local product_name="$1"; shift
	local hw_configurable="$1"; shift
	local language_configurable="$1"; shift

	if [[ ! -f "$config" ]]
 	then
 		/bin/mkdir -p "$(dirname "$config")"
		/bin/touch "$config"
 	fi

	addOrReplaceSectionLine "$config" "$product_id" "DisplayName" "$product_name"
	addOrReplaceSectionLine "$config" "$product_id" "IsHwConfigurable" "$hw_configurable"
	addOrReplaceSectionLine "$config" "$product_id" "IsLanguageConfigurable" "$language_configurable"

	local i=0
	local key_name
	while [ $# -gt 0 ]
	do
		if (( i == 0 ))
 		then
			key_name="LanguagesFolder"
		else
			key_name="LanguagesFolder$i"
		fi

		addOrReplaceSectionLine "$config" "$product_id" "${key_name}" "$1"

		shift
		(( i++ )) || true
	done

	logCommand "RemoveRecordForLanguageSetup \"$config\" \"$product_id\""
}

function RemoveRecordForLanguageSetup()
{
	local config="$1"; shift
	local product_id="$1"; shift

	removeMatchingSectionKeys "$config" "$product_id" ".*"
}

function SetupQtConfigPaths()
{
	local qt_config="$1"; shift
	local plugin_path="$1"; shift
	local settings_path="$1"; shift

	if [[ ! -f "${qt_config}" ]]
	then
		mkdirs "$(dirname "${qt_config}")"
		/bin/touch "${qt_config}"
		logFile "${qt_config}"
	fi

	addOrReplaceSectionLine "${qt_config}" "Paths" "Plugins" "${plugin_path}"
	addOrReplaceSectionLine "${qt_config}" "Paths" "Settings" "${settings_path}"
}

##########################################################################################################

function GetDesktopVersions()
{
	export XSESSION_AVAILABLE="false"
	export XINITRC_AVAILABLE="false"
	if [[ -x "/etc/X11/Xsession" ]] && [[ -d "/etc/X11/Xsession.d" ]]
	then
		XSESSION_AVAILABLE="true"
	elif [[ -x "/etc/X11/xinit/xinitrc" ]] && [[ -d "/etc/X11/xinit/xinitrc.d" ]]
	then
		XINITRC_AVAILABLE="true"
	fi

	export KDE_VERSION="NOKDE"
	if which ksmserver &> /dev/null
	then
		KDE_VERSION=$( ksmserver --version | grep KDE | sed '{s/[a-zA-Z]//g; s/\ //g; s/\://g; s/\"//g}' )
	fi

	export GNOME_VERSION="NOGNOME"
	local gnome_lib="$(/sbin/ldconfig -p | grep -m 1 libgnome-2 | sed "s/.*=> //")"

	while [[ -h "$gnome_lib" ]]
	do
		gnome_lib_tmp="$(ls -l "$gnome_lib" | sed "s/.*-> //")"
		if [[ "${gnome_lib_tmp:0:1}" != "/" ]]
		then
			gnome_lib_tmp="$(dirname "$gnome_lib")/$gnome_lib_tmp"
		fi
		gnome_lib="$gnome_lib_tmp"
	done

	if [[ -f "$gnome_lib" ]]
	then
		GNOME_VERSION="$(echo "$gnome_lib" | sed "s/.*\.so\.//")"
	elif [[ "x$gnome_lib" != "x" ]]
	then
		echo "Failed to detect Gnome version: $gnome_lib" >&2
	fi
}

function MakeKDEAutostart()
{(
	local user="$1"; shift
	local group="$1"; shift
	local home="$1"; shift
	local file_name="$1"; shift

	if [[ "$user" != "0" ]] && [[ "$user" != "root" ]]
	then
		if [[ ! -e "$home/.kde/Autostart" ]]
		then
			/bin/mkdir -p "$home/.kde/Autostart"
			/bin/chown "$user:$group" "$home/.kde/Autostart"
		fi
	else
		if [[ ! -d "$home/.kde/Autostart" ]]; then return 1; fi
	fi

	{
		echo '#!/bin/bash'
		while [ $# -gt 0 ]
		do
			local executable="$1"; shift
			echo "\"$executable\" &"
		done
	} > "$home/.kde/Autostart/$file_name"

	/bin/chown "$user:$group" "$home/.kde/Autostart/$file_name"
	/bin/chmod 755 "$home/.kde/Autostart/$file_name"
	logFile "$home/.kde/Autostart/$file_name"
)}

function MakeNewGnomeAutostart()
{
	local user="$1"; shift
	local group="$1"; shift
	local home="$1"; shift
	local file_name="$1"; shift

	/bin/mkdir -p "$home/.config"

	if [[ "$user" != "0" ]] && [[ "$user" != "root" ]]
	then
		/bin/chown "$user:$group" "$home/.config"
		if [[ ! -e "$home/.config/autostart" ]]
		then
			/bin/mkdir -p "$home/.config/autostart"
			/bin/chown "$user:$group" "$home/.config/autostart"
		fi
	else
		if [[ ! -d "$home/.config/autostart" ]]; then return 1; fi
	fi

	while [ $# -gt 0 ]
	do
		local executable="$1"; shift
		local desktop_name="${file_name}.desktop"
		local desktop_path="$home/.config/autostart/$desktop_name"
		{
			echo '[Desktop Entry]'
			echo "Name=$(basename "$executable")"
			echo 'Encoding=UTF-8'
			echo 'Version=1.0'
			echo 'X-GNOME-Autostart-enabled=true'
			echo "Exec=\"$executable\""
			echo 'Type=Application'
			echo 'Icon=system-run'
			echo 'Comment=SMART Software'
		} > "$desktop_path"
		/bin/chown $user:$group "$desktop_path"
		/bin/chmod 755 "$desktop_path"
		logFile "$desktop_path"
	done
}

function IsVersionLess()
{(
	local ver1=$1
	local ver2=$2

	OLD_IFS="$IFS"
	IFS=" "

	ver1=( $(echo "${ver1//\./ }") )
	ver2=( $(echo "${ver2//\./ }") )

	IFS="$OLD_IFS"

	local max=$(( ${#ver1[@]} > ${#ver2[@]} ? ${#ver1[@]} : ${#ver2[@]} ))
	local i=0

	while (( i < max ))
	do
		if (( ${ver1[i]:0} < ${ver2[i]:0} )); then return 0; fi
		if (( ${ver1[i]:0} > ${ver2[i]:0} )); then return 1; fi

		(( i++ )) || true
	done

	return 1
)}

function RunForAllUsers()
{
	local command="$1"; shift

	local IFS=$'\n'
	for entry in $(cat /etc/passwd | cut -s -f3,4,6,7 -d":" | grep -v /sbin/nologin | grep -v /bin/false | cut -s -f1,2,3 -d":")
	do
		local home_dir="${entry#*:*:}"
		local user_group="${entry%:*}"
		local user="${user_group%:*}"
		local group="${user_group#*:}"

		if [[ ! -d "${home_dir}/.config" ]]; then continue; fi
		if [[ -z "${user}" ]]; then continue; fi
		if [[ "${user}" == "0" ]]; then continue; fi
		if [[ -z "${group}" ]]; then continue; fi
		if [[ "${group}" == "0" ]]; then continue; fi

		"${command}" "${user}" "${group}" "${home_dir}" "$@"
	done
}

function MakeXSessionAutostart()
{
	local file_name="$1"; shift
	local priority="$1"; shift

	local root="/etc/X11/Xsession.d"

	local escaped_file_name="$( basename "${file_name}" | sed "s# #-#g" )"
	local script_name="98smart_${priority}-${escaped_file_name}"

	echo "" > "${root}/${script_name}"

	while [ $# -gt 0 ]
	do
		local executable="$1"; shift
		echo "\"${executable}\" &" >> "${root}/${script_name}"
	done

	logFile "${root}/${script_name}"
}

function MakeXinitrcAutostart()
{
	local file_name="$1"; shift
	local priority="$1"; shift

	local root="/etc/X11/xinit/xinitrc.d"

	local escaped_file_name="$( basename "${file_name}" | sed "s# #-#g" )"
	local script_name="98smart_${priority}-${escaped_file_name}.sh"

	echo "" > "${root}/${script_name}"

	while [ $# -gt 0 ]
	do
		local executable="$1"; shift
		echo "\"${executable}\" &" >> "${root}/${script_name}"
	done

	chmod +x "${root}/${script_name}"
	logFile "${root}/${script_name}"
}

function MakeAutostart()
{(
	local user="$1"; shift
	local group="$1"; shift
	local home="$1"; shift
	local file_name="$1"; shift

	if [[ -n "$NO_SB_AUTOSTART" ]]; then return 0; fi

	GetDesktopVersions

	if [[ "${XSESSION_AVAILABLE}" == "true" ]]
	then
		MakeXSessionAutostart "${file_name}" 1 "$@"
		return $?
	elif [[ "${XINITRC_AVAILABLE}" == "true" ]]
	then
		MakeXinitrcAutostart "${file_name}" 1 "$@"
		return $?
	fi

	if [[ "$KDE_VERSION" != "NOKDE" ]]
	then
		RunForAllUsers MakeKDEAutostart "$file_name" "$@"
	fi

	if [[ "$GNOME_VERSION" != "NOGNOME" ]]
	then
		if IsVersionLess "$GNOME_VERSION" "0.1400.0"
		then
			echo "Autostart for Gnome older than 2.14 is not implemented" &>2
		else
			RunForAllUsers MakeNewGnomeAutostart "$file_name" "$@"
		fi
	fi
)}

##########################################################################################################

function ReloadUdevRules()
{
	if [[ -x /sbin/udevadm ]]
	then
		/sbin/udevadm control --reload-rules
		return $?
	elif [[ -x /sbin/udevcontrol ]]
	then
		/sbin/udevcontrol reload_rules
		return $?
	else
		return 1
	fi
}

##########################################################################################################

MatchLanguageToSBLanguage()
{
	a=$(getLanguages)
	if [[ ! $? ]];
	then
		export SB_LANG="${LANGUAGEDEFAULT}"
		return
	fi

	for word in $a;
	do
		case $word in
		en_*) export SB_LANG="en_CA";;
		ca_*) export SB_LANG="ca";;
		de_*) export SB_LANG="de";;
		es_*) export SB_LANG="es";;
		eu_*) export SB_LANG="eu";;
		fi_*) export SB_LANG="fi";;
		fr_*) export SB_LANG="fr";;
		gl_*) export SB_LANG="gl";;
		it_*) export SB_LANG="it";;
		nb_*) export SB_LANG="nb";;
		sv_*) export SB_LANG="sv";;
		*) export SB_LANG="$word";;
		esac
	done

	if [[ -z "$SB_LANG" ]];
	then
		export SB_LANG="${LANGUAGEDEFAULT}"
	fi

#echo "Locale: $SB_LANG"
}

LANGUAGEDEFAULT="en_CA"

# Figure out language install is running in and match it with a suitable SB language
outputStatus_L()
{
	OLD_IFS="$IFS"
	IFS=$'\n'  # To print each array element on a separate line

	STRINGARRAY="$2[*]" #get stuff of array passed in
	local ${!STRINGARRAY} #makes names of things in array availiable to here

	IFS="$OLD_IFS"

	language_var="$1"

	if [[ -z "$(eval "\${$language_var}")" ]]
	then
		language_var="$(eval echo \$$LANGUAGEDEFAULT)"
	fi

	outputStatus "${language_var}"
}

outputFail_L()
{
	OLD_IFS="$IFS"
	IFS=$'\n'  # To print each array element on a separate line

	STRINGARRAY="$2[*]" #get stuff of array passed in
	local ${!STRINGARRAY} #makes names of things in array availiable to here

	IFS="$OLD_IFS"

	language_var="$1"

	if [[ -z "$(eval "\${$language_var}")" ]]
	then
		language_var="$(eval echo \$$LANGUAGEDEFAULT)"
	fi

	outputFail "${language_var}"
}

export SB_LANG=""
MatchLanguageToSBLanguage

##########################################################################################################

##########################################################################################################
if [[ ! -e "$SMARTTECHCONFNAME" && -e "$OLD_SMARTTECHCONFNAME" ]]
then
	/bin/cp "$OLD_SMARTTECHCONFNAME" "$SMARTTECHCONFNAME"
fi

/bin/mkdir -p "$(dirname "$SMARTTECHCONFNAME")"
/bin/touch "$SMARTTECHCONFNAME"
/bin/chmod 666 "$SMARTTECHCONFNAME"
/bin/mkdir -p "$(dirname "$NOTEBOOK_CONFIG")"
/bin/touch "$NOTEBOOK_CONFIG"
/bin/chmod 666 "$NOTEBOOK_CONFIG"
##########################################################################################################

########################################################################
# Substituted: install marker
{ echo "debian"; echo "${package_name}"; } > "${PREFIX}/.${autopackage_short_name}"
logFile "${PREFIX}/.${autopackage_short_name}"
# /Substituted
########################################################################

	ACTIVATION_DIR="${PREFIX}/Activation Wizard"

	copyFiles dist/* "${INSTALL_DIR}/."
	copyFiles activation/* "${ACTIVATION_DIR}/."
	updateEnv --append PATH "${INSTALL_DIR}/bin"

	SlaughterOnUninstall "${INSTALL_DIR}/bin"

# HACK
	/bin/rm -f "${INSTALL_DIR}/bin/Notebook/qt.conf"
	/bin/touch "${INSTALL_DIR}/bin/Notebook/qt.conf"
	SetupQtConfigPaths "${INSTALL_DIR}/bin/Notebook/qt.conf" "${PREFIX}/common/plugins" "/etc/xdg"

	CreateXmlForSPU SoftwareUpdateNbk
	CreateRecordForLanguageSetup "${LANGUAGE_SETUP_CONFIG}" "Notebook" "Notebook Software" "1" "1" "${INSTALL_DIR}/bin/Notebook/resources/Languages" "${INSTALL_DIR}/Languages" "${ACTIVATION_DIR}/Languages"

	if [[ -f /usr/bin/chcon ]]
	then
# HACK: untill I figure out what's wrong with it
		Execute . /usr/bin/chcon -t texrel_shlib_t "${INSTALL_DIR}/bin/Notebook/supportlibs/libruby.so.1.8" 2> /dev/null
	fi

	addOrReplaceSectionLine "$SMARTTECHCONFNAME" "Software" "SMART%20Technologies\Notebook%20Software\Install%20Information\NotebookExePath" "${INSTALL_DIR}"
	addOrReplaceSectionLine "$SMARTTECHCONFNAME" "Software" "SMART%20Technologies\Notebook%20Software\Install%20Information\Notebook%20Version" "${SOFTWAREVERSION}"
	addOrReplaceSectionLine "$SMARTTECHCONFNAME" "Software" "SMART%20Technologies\Notebook%20Software\Install%20Information\Documentation" "${INSTALL_DIR}/bin/Notebook/documentation"
	addOrReplaceSectionLine "$NOTEBOOK_CONFIG" "Software" "SMART%20Technologies\Gallery\GallerySamplerManifest" "${INSTALL_DIR}/Gallery/imsmanifest.xml"

	if [[ "${debian_script:-"false"}" != "true" ]]
	then
		temp_path="./temp"
	else
		temp_path="${_store_dir}/temp"
	fi
	Execute "${PREFIX}/common/lib" "${temp_path}/goodbyeworld" --trial --puid=clash_notebook

	PrepareXdgUtils "${PREFIX}/common/xdg"
	PrepareDesktopFiles xdg/menu-desktop "${INSTALL_DIR}/bin"
	PrepareDesktopFiles xdg/menu-desktop-tools "${INSTALL_DIR}/bin"
	PrepareDesktopFiles xdg/mime-desktop "${INSTALL_DIR}/bin"
	PrepareDesktopFiles xdg/autopackage-desktop "${INSTALL_DIR}/bin"

	installIcon xdg/themes/hicolor
	installDesktop "X-smarttech-software" xdg/autopackage-desktop/notebook.desktop

	InstallMimes xdg/mime "${INSTALL_DIR}/."
	InstallDesktops xdg/mime-desktop "${INSTALL_DIR}/installdata/menus"
	InstallDesktops xdg/menu-desktop "${INSTALL_DIR}/installdata/menus" \
				xdg/desktop-directories/smarttech-software.directory \
					xdg/desktop-directories/smarttech-software-notebook.directory
	InstallDesktops xdg/menu-desktop-tools "${INSTALL_DIR}/installdata/menus" \
				xdg/desktop-directories/smarttech-software.directory \
					xdg/desktop-directories/smarttech-software-notebook.directory \
						xdg/desktop-directories/smarttech-software-tools.directory
	UpdateDesktops

	if [[ "$MAIN_PACKAGE" == "$SHORTNAME" ]]
	then
		RunActivation
		RunGallerySetup
	fi

}

# /Inserted autopackage specific script
##############################################
##AUTOPACKAGE_IMPORT_END##


##############################################
# Inserted: event handler framework 

###############################################################
# framework for rpm

# This line is a debugging aid to just copy files w/o doing any scripting
[ ${RPM_MAINTAINER_NOSCRIPTS:-null} != null ] && exit 0

# This line is a debugging aid to set tracing
[ ${RPM_DEBUG_SCRIPTS:-null} != null ] && echo rpmdebugging  &&  set -x


#set -e
# The function name gets set by the generator, so the framework is unique
#_function=postun

_logfile=smart_rpm_install.log
[ ${RPM_MAINTAINER_LOGPATH:-null} != null ] && _logfile=${RPM_MAINTAINER_LOGPATH}/$_logfile || _logfile=/root/$_logfile

# know thyself 
_self="$_package.$_version.$_function"
[ -z "$_self" ] && _self="$0"

# state thy business
if [ ${RPM_MAINTAINER_LOG:-null} != null ]; then
    	echo "$(date) $_self $*" >> $_logfile 
fi

#=========================================================================
#
# find out the will of the gods
#
#
#case $_function in
#pre|post)
#	nr_after=$1
#	nr_before=(( $nr_after - 1 ))
#	[ $nr_before -eq 0 ] && FIRST_INSTANCE= true && UPGRADING= 0
#	[ $nr_before -gt 0 ] && FIRST_INSTANCE= false && UPGRADING= 1
#	;;
#preun|postun)
#	nr_after=$1
#	nr_before=(( $nr_after + 1 ))
#	[ $nr_after -eq 0 ] && LAST_INSTANCE= true
#	[ $nr_after -gt 0 ] && FIRST_INSTANCE= false
#	UPGRADING=0
#	;;
#esac
#
#INSTALL_RUNNING=$UPGRADING

all_action
_status=$?
exit $_status



#
###########
#
# END OF SCRIPT
#
###############################################################
# /Inserted event handler framework 
##############################################
