#!/bin/sh

# System: http://www.pathname.com/fhs/
# User-space: http://www.csis.gvsu.edu/~abreschm/uafhs/

# These are the only variables that need to be changed:
opera_version=9.51
debug_level='0'			# From 0 to 2

# Everything else should look after itself:
str_progname="install.sh"
str_defaultprefix="/usr"
OPERADESTDIR=''

unset CDPATH

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

debug_msg()
{
    # This function outputs a stylish debug message if debug is enabled
    # $1 = debuglevel
    # $2 = message

    if test "$debug_level" -gt "$1"; then echo " $str_progname: debug: $2"; fi
}

error()
{
    # This function displays a error message and exits abnormally.
    # Arg_1 = Error Type
    # Arg_2 = Error Message

    debug_msg 0 'in error()'

    case $1 in

	missing)
	    echo " $str_progname: missing parameter(s)"
	    echo
	    usage
	    ;;

	invalid)
	    echo " $str_progname: invalid parameter(s)"
	    echo
	    usage
	    ;;

	abort)
	    echo " $str_progname: installation aborted by user"
	    ;;

	conflict)
	    echo " $str_progname: conflicting parameters"
	    echo
	    usage
	    ;;

	access)
	    echo " $str_progname: You do not have write access to $2, please change to appropriate user."
	    ;;

        uname)
	    echo " $str_progname: OS cannot be determined without the program \"uname\", aborting..."
	    ;;

	umask)
	    echo " $str_progname: your umask," `umask`, "would create a broken installation."
	    echo " Run umask 022 to change it, then try again."
	    ;;

	sed)
	    echo " $str_progname: Install script will not work without the program \"sed\", aborting..."
	    ;;
	os)
	    echo " $str_progname: Unrecognizeed platform ($machine) and OS ($os), aborting..."
	    echo " $str_progname: Please send output of uname -a to packager\@opera.com"
	    echo " mentioning Opera version $opera_version"
	    ;;

	*)
	    debug_msg 0 "Error message $1 not defined, aborting..."
	    ;;
    esac >&2
    exit 1
}

guess_os()
{
    # This function tries to guess which OS the install Machine is running.
    # other ideas are $OSTYPE, arch
    # Return = $os

    os=`uname -s` || error 'uname'
    case $os in
	FreeBSD|NetBSD|DragonFly) os=AnyBSD;;
	SunOS*) os=SunOS;;
    esac
    case $os in SunOS|AnyBSD|OpenBSD) str_defaultprefix="/usr/local";; esac

    machine=`uname -m`
    case $machine in
	# Canonicalize architecture names with aliases:
	sun*|sparc*) machine=sparc;;
	amd64) machine=x86_64;;
	i[3456]86|i86pc|x86pc) machine=x86;;
    esac
}

check_prefixes()
{
    # This function checks system enviroment for install prefix locations
    # and sets prefixed installation paths.

    export prefix exec_prefix wrapperdir docdir sharedir plugindir man_dir

    debug_msg 0 "in check_prefixes()"
    debug_msg 1 "enviroment = $prefix $exec_prefix $wrapperdir $docdir $sharedir $plugindir $man_dir"

    verbose="0"

    guess_os

    # Solaris's /bin/sh's built-in umask doesn't fail when invoked
    # with -S but doesn't honour -S, either; while GNU/Linux has no
    # /usr/bin/umask so we must rely on its built-in, which *does*
    # support -S.
    case `ls -1 /usr/bin/umask 2>/dev/null` in /usr/bin/umask) /usr/bin/umask -S ;; *) umask -S ;; esac \
	| tr , '\012' | grep 'o=rw*x' >/dev/null 2>&1 || error umask
    if test "$#" -ne 0; then parse_input "$@"; fi
}

set_prefix()
{
    # Arg 1 = new prefix
    prefix="$1"

    test "${prefix}" || prefix="${str_defaultprefix}"

    share_dir="${prefix}/share/opera"
    case "$os" in
	AnyBSD|OpenBSD)
	    exec_dir="${share_dir}/bin"
	    plugin_dir="${share_dir}/plugins"
	    man_dir="$prefix/man"
	    ;;
	*)
	    exec_dir="${prefix}/lib/opera/$opera_version"
	    plugin_dir="${prefix}/lib/opera/plugins"
	    man_dir="$prefix/share/man"
	    ;;
    esac
    doc_dir="${prefix}/share/doc/opera"
    wrapper_dir="${prefix}/bin"
}

set_destdir()
{
    test "$1" || return 1
    OPERADESTDIR="$1"
    exec_dir="${OPERADESTDIR}${exec_dir}"
    wrapper_dir="${OPERADESTDIR}${wrapper_dir}"
    doc_dir="${OPERADESTDIR}${doc_dir}"
    man_dir="${OPERADESTDIR}${man_dir}"
    share_dir="${OPERADESTDIR}${share_dir}"
    plugin_dir="${OPERADESTDIR}${plugin_dir}"
}

usage()
{
    # This function displays the help information.

    debug_msg 0 "in usege()"

    echo "Usage: $str_progname -s"
    echo "  or:  $str_progname -f DEST"
    if test "$1"
    then
	 echo "  or:  $str_progname -f EXEC_DEST WRAPPER_DEST DOC_DEST SHARE_DEST PLUGIN_DEST MAN_DEST"
	 echo "  or:  $str_progname --prefix=DEST [--exec_prefix=] [--wrapperdir=] [--docdir=] [--sharedir=] [--plugindir=] [--mandir=]"
    else echo "  or:  $str_progname --prefix=DEST"
    fi
    echo "  or:  $str_progname --exec_prefix=EXEC_DEST --wrapperdir=WRAPPER_DEST --docdir=DOC_DEST --mandir=MAN_DEST --sharedir=SHARE_DEST --plugindir=PLUGIN_DEST"
    if test "$1"
    then
	echo
	echo ' or by enviroment variables:'
	echo "  or:  prefix=DEST ${str_progname}"
	echo "  or:  export prefix=DEST; ${str_progname}"
    fi
    echo
    echo 'Install Opera files to standard or user defined locations.'
    echo
    echo '  -i, --interactive            Interactive mode (default)'
    echo
    echo '  -s, --standard               install to standard locations'
    echo '  -f, --force                  install to user defined location(s)'
    echo
    test "$1" && echo '      $prefix'
    echo '      --prefix=                install all files to directory'
    echo
    test "$1" && echo '      $exec_prefix'
    echo '      --exec_prefix=           install Opera binaries to directory'
    test "$1" && echo '      $wrapperdir'
    echo '      --wrapperdir=            install Opera wrapper script to directory'
    test "$1" && echo '      $docdir'
    echo '      --docdir=                install Opera documentation to directory'
    test "$1" && echo '      $man_dir'
    echo '      --mandir=                install Opera manual page to directory'
    test "$1" && echo '      $sharedir'
    echo '      --sharedir=              install Opera shared files to directory'
    test "$1" && echo '      $plugindir'
    echo '      --plugindir=             install Opera plugin files to directory'
    echo
    echo '  -v, --verbose                output which files are copied'
    echo '  -vv                          output info on each executed command'
    echo
    echo '  -V, --version                output version information and exit'
    echo '  -h, --help                   display this help and exit'
    echo '      --help=long              show advanced functions'
    echo
    echo 'If you choose to do a standard locations install, files will be put into'
    echo '/usr/bin, /usr/share/doc/opera and /usr/share/opera.'
    echo
    echo 'However, if you choose to install to user defined locations, you must either'
    echo '  specify one directory (all files will be put in this directory), or'
    echo '  specify five directories (you may enter the same directory several times).'
}

parse_input()
{
    # This function parses trough command line parameters
    # and sets install flags and selected installation paths.

    debug_msg 0 "in parse_input()"
    debug_msg 1 "args = $*"


while test ! -z "$1"
do
case $1 in

    -h|--help) usage; exit 0 ;;

    --help=long) usage long; exit 0 ;;

    -V|--version) version; exit 0 ;;

    -v|--verbose)
	verbose='1'
	shift
	;;

    -vv)
	verbose='2'
	shift
	;;

    -i|--interactive)
	if test -z "$flag_mode"
	then
	    flag_mode='--interactive'
	    shift
	else error 'conflict'
	fi
	;;


    -s|--standard)
	if test -z "$flag_mode"
	then
	    flag_mode='--standard'
	    shift
	else error 'conflict'
	fi
	;;

    -f|--force)
	if test -z "$flag_mode"
	then
	    flag_mode='--force'
	    shift
	    if test -z "$1"
	    then error 'missing'
	    elif test -z "$2"
	    then
		str_paramprefix=`echo "$1" | sed -e 's/--prefix=//'`
		warn "Only one destination parameter found, all files will be installed to ${str_paramprefix}"
		warn 'Do you want to continue [y/n]?'
		read continue
		if test "${continue}" != 'y' && test "${continue}" != 'Y'
		then error 'abort'
		else shift
		fi
	    elif test -z "$6"
	    then error 'missing'
	    else
		str_paramexec="$1"
		str_paramwrapper="$2"
		str_paramdoc="$3"
		str_paramshare="$4"
		str_paramplugin="$5"
		str_paramman="$6"
		shift 6
	    fi
	else error 'conflict'
	fi
	;;

    DESTDIR=*)
	    param=`echo "$1" | sed -e 's/DESTDIR=//'`
	    shift
	    test "${param}" && str_paramdestdir="$param"
	    ;;

    --DESTDIR=*)
	    param=`echo "$1" | sed -e 's/--DESTDIR=//'`
	    shift
	    test "${param}" && str_paramdestdir="$param"
	    ;;

    --prefix=*)
	    param=`echo "$1" | sed -e 's/--prefix=//'`
	    shift
	    if test "${param}"
	    then
		if test "$flag_mode" = '--prefix=' ||  test -z "$flag_mode"
		then
		    flag_mode='--prefix='
		    str_paramprefix="${param}"
		else error 'conflict'
		fi
	    fi
	    ;;

    --exec_prefix=*)
	    param=`echo "$1" | sed -e 's/--exec_prefix=//'`
	    shift
	    if test "${param}"
	    then
		if test "$flag_mode" = '--prefix=' || test -z "$flag_mode"
		then
		    flag_mode='--prefix='
		    str_paramexec="${param}"
		else error 'conflict'
		fi
	    fi
	    ;;

    --wrapperdir=*)
	    param=`echo "$1" | sed -e 's/--wrapperdir=//'`
	    shift
	    if test "${param}"
	    then
		if test "$flag_mode" = '--prefix=' || test -z "$flag_mode"
		then
		    flag_mode='--prefix='
		    str_paramwrapper="${param}"
		else error 'conflict'
		fi
	    fi
	    ;;

    --mandir=*)
	    param=`echo "$1" | sed -e 's/--mandir=//'`
	    shift
	    if test "${param}"
	    then
		if test "$flag_mode" = '--prefix=' || test -z "$flag_mode"
		then
		    flag_mode='--prefix='
		    str_paramman="${param}"
		else error 'conflict'
		fi
	    fi
	    ;;

    --docdir=*)
	    param=`echo "$1" | sed -e 's/--docdir=//'`
	    shift
	    if test "${param}"
	    then
		if test "$flag_mode" = '--prefix=' || test -z "$flag_mode"
		then
		    flag_mode='--prefix='
		    str_paramdoc="${param}"
		else error 'conflict'
		fi
	    fi
	    ;;

    --sharedir=*)
	    param=`echo "$1" | sed -e 's/--sharedir=//'`
	    shift
	    if test "${param}"
	    then
		if test "$flag_mode" = '--prefix=' || test -z "$flag_mode"
		then
		    flag_mode='--prefix='
		    str_paramshare="${param}"
		else error 'conflict'
		fi
	    fi
	    ;;

    --plugindir=*)
	    param=`echo "$1" | sed -e 's/--plugindir=//'`
	    shift
	    if test "${param}"
	    then
		if test "$flag_mode" = '--prefix=' || test -z "$flag_mode"
		then
		    flag_mode='--prefix='
		    str_paramplugin="${param}"
		else error 'conflict'
		fi
	    fi
	    ;;

     *) error 'invalid';;
esac
done
    debug_msg 1 "flag_mode = $flag_mode"
}

set_os_spesific()
{
    # This function determines which commands and parameters will work on a given platform.

    case "$os" in
	SunOS)
	    cpf=''    # SunOS cp overwrites by default (no -f force option)
	    cpv=''    # SunOS cp (no -v verbose option)
	    chmodv='' # SunOS chmod (no -v verbose option)
	    mkdirv='' # SunOS mkdir (no -v verbose option)
	    mvv=''    # SunOS mv (no -v verbose option)
	;;

	AnyBSD)
		cpf='-f'
		if test "$verbose" -gt '1'
		then
		    chmodv='-v'
		    mkdirv='-v'
		fi
		if test "$verbose" -gt '0'
		then
		    mvv='-v'
		    cpv='-v'
		fi
	;;

	OpenBSD|QNX)
	    cpf='-f'
	    mkdirv=''
	    chmodv=''
	    cpv=''
	    mvv=''
	;;

	Linux)
		cpf='-f'
		if test "$verbose" -gt "1"
		then
		    chmodv='-v'
		    mkdirv='--verbose'
		else # in case of csh
		    chmodv=''
		    mkdirv=''
		fi
		if test "$verbose" -gt "0"
		then
		    mvv='-v'
		    cpv='-v'
		else # in case of csh
		    mvv=''
		    cpv=''
		fi
	;;

	*) error 'os';;
    esac
    debug_msg 1 "cpf = $cpf"
    debug_msg 1 "cpv = $cpv"
    debug_msg 1 "chmodv = $chmodv"
    debug_msg 1 "mkdirv = $mkdirv"

    # Common
    mkdirp='-p -m 755'
    cpp='-p'
    cpR='-R'
    lns='-s'
}

version()
{
    # This function displays the version information.

    debug_msg 0 'in version()'

    echo "${str_progname} (Opera Software ASA) 3.98"
    echo 'Maintained by Opera packaging team <packager@opera.com>'
    echo
    echo 'Copyright (C) 2001-2007 Opera Software ASA.'
    echo 'This is free software; there is NO warranty; not even'
    echo 'for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.'
}

con_firm()
{
    str_options="[ y,n | yes,no ]"
    test "$2" && str_options="[ y,n,c | yes,no,cancel ]"
    echo "$1 ${str_options} ?"
    while true
    do
      read str_answer
      case "${str_answer}" in

	    ''|[yY]|[yY][eE][sS])
		return 0
		;;

	    [nN]|[nN][oO])
		return 1
		;;

	    [aAcCqQ]|[aA][bB][oO][rR][tT]|[cC][aA][nN][cC][eE][lL]|[qQ][uU][iI][tT])
		if test "$2"
		then error "abort"
		else warn 'Invalid answer, try again:'
		fi
		;;

	    *)
		warn 'Invalid answer, try again:'
		;;

      esac
    done
}

ver_bose()
{
    if test "${verbose}" = "0"; then return 1; fi
}

select_installation_type()
{
    # This function parses installation flags and sets final installation paths.

    debug_msg 0 'in select_installation_type()'
    debug_msg 1 "flag_mode = ${flag_mode}"

    if test -z "${flag_mode}"
    then
	if test "${str_paramdestdir}"
	then flag_mode='--prefix='
	else flag_mode='--interactive'
	fi
    fi

    set_prefix "${prefix}"
    test "${exec_prefix}" && exec_dir="${exec_prefix}"
    test "${wrapperdir}"  && wrapper_dir="${wrapperdir}"
    test "${docdir}"      && doc_dir="${docdir}"
    test "${sharedir}"    && share_dir="${sharedir}"
    test "${plugindir}"   && plugin_dir="${plugindir}"

    case $flag_mode in

	--interactive)
	    if ver_bose; then echo 'Running interactive installation...'; fi
	    interactive_install
	    ;;

	--standard)
	    if ver_bose; then echo 'Running standard installation...'; fi
	    set_prefix "${str_defaultprefix}"
	    set_destdir "${str_paramdestdir}"
	    ;;

	--force)
	    if ver_bose; then echo 'Running forced installation...'; fi
	    set_prefix "${str_paramprefix}"
	    set_destdir "${str_paramdestdir}"
	    ;;

	--prefix=)
	    if ver_bose; then echo 'Running prefixed installation...'; fi
	    set_prefix "${str_paramprefix}"
	    test "${str_paramexec}"     && exec_dir="${str_paramexec}"
	    test "${str_paramwrapper}"  && wrapper_dir="${str_paramwrapper}"
	    test "${str_paramdoc}"      && doc_dir="${str_paramdoc}"
	    test "${str_paramman}"      && man_dir="${str_paramman}"
	    test "${str_paramshare}"    && share_dir="${str_paramshare}"
	    test "${str_paramplugin}"   && plugin_dir="${str_paramplugin}"
	    set_destdir "${str_paramdestdir}"
	    ;;
    esac
}

can_write_to()
{
    # This function checks write access on paths
    # Returns (0 true writeable) or (1 false unwriteable)

    # Arg1 = directory to test

    debug_msg 0 'in can_write_to()'
    for arg # implicitly in "$@"
    do
	debug_msg 1 " $arg"
	test_folder="$arg"

	# If directory doesn't exist go up once and test again
	while test ! -d "${test_folder}"
	do
	    temp_folder=`echo ${test_folder} | sed -e 's:/[^/]*$::'`
	    # If nothing removed, avoid infinite loop
	    if test "${temp_folder}" = "${test_folder}"; then break; fi
	    test_folder="${temp_folder}"
	    debug_msg 1 " ${test_folder}"
	done

	if test -w "${test_folder}"
	then
	    debug_msg 1 "User \"${USERNAME}\" has write access to [${test_folder}]"
	else
	    debug_msg 1 "User \"${USERNAME}\" can't write to [${test_folder}]"
	    return 1
	fi
    done
}

cannot_write_to()
{
    # Needed for the while loop in prompt_path because Solaris sh doesn't like ! as negation.
    if can_write_to "$@"
    then return 1
    else return 0
    fi
}

confirm_paths()
{
    while true
    do
      echo
      echo "Files shall be installed as follows:"
      echo "-----------------------------------------------------------"
      echo " Wrapper Script : ${wrapper_dir}"
      echo " Binaries       : ${exec_dir}"
      echo " Plugins        : ${plugin_dir}"
      echo " Shared files   : ${share_dir}"
      echo " Documentation  : ${doc_dir}"
      echo " Manual page    : ${man_dir}"
      echo "-----------------------------------------------------------"
      if con_firm "Is this correct" "cancel"
      then return 0
      else change_paths
      fi
    done
}

csh_set()
{
    # This funtion enables csh syntax for the set command.
    # Read more at http://zsh.sunsite.dk/Intro/intro_12.html
    eval "$1$2$3"
}

chop()
{
    str_toremove="$1"
    str_varname="$2"
    eval str_from=\$"${str_varname}"
    str_removed=""

    while test "$str_toremove"
    do
	str_toremove=`echo "${str_toremove}"|sed -e 's/.//'`
	str_removed="${str_removed}`echo "${str_from}"|sed -e 's/\(.\).*/\1/'`"
	str_from=`echo "${str_from}"|sed -e 's/.//'`
    done

    test "${str_removed}" = "$1" && eval ${str_varname}="${str_from}"
}

prompt_path()
{
    # This function suggests a path and test new if user changes
    # Arg 1 = type of files
    # Arg 2 = path to test
    # Arg 3 = variable to modify

    if test "$1" = 'prefix'
    then echo "Enter installation prefix [${prefix}]"
    else echo "Enter path for the Opera $1 [$2]"
    fi

    read a_path

    test "${a_path}" || a_path="$2"
    while cannot_write_to "${a_path}"
    do
	echo "User \"${USERNAME}\" does not have write access to [${a_path}]."
	if test "$1" = 'prefix'
	then echo "Enter installation prefix [$2]"
	else echo "Enter path for the Opera $1 [$2]"
	fi
	read a_path
	if test -z "${a_path}"; then return; fi
    done
    if test "$1" = 'prefix'
    then set_prefix "${a_path}"
    else csh_set  "$3"="${a_path}"
    fi
}

change_paths()
{
    prompt_path "prefix" "${prefix}" 'prefix'
    prompt_path "wrapper script" "${wrapper_dir}" "wrapper_dir"
    prompt_path "binaries" "${exec_dir}" "exec_dir"
    prompt_path "plugins" "${plugin_dir}" "plugin_dir"
    prompt_path "shared files" "${share_dir}" "share_dir"
    prompt_path "documentation" "${doc_dir}" "doc_dir"
    prompt_path "manual page" "${man_dir}" "man_dir"
}

interactive_install()
{
    # This function starts of checking if you have access to
    # prefix location
    # default locations (/usr)
    # ${HOME}

    # Test current prefixed locations.
    if test -n "${prefix}"
    then
	if can_write_to "${exec_dir}" "${wrapper_dir}" "${doc_dir}" "${share_dir}" "${plugin_dir}" "${man_dir}"
	then
	  # Prefix location success -> Recommend prefix install
	    if ver_bose; then echo "User \"${USERNAME}\" has write access to current prefixed locations."; fi
	    confirm_paths
	    return
	else
	  # Prefix location failed -> Try default
	    if ver_bose
	    then
		warn "User \"${USERNAME}\" does not have write access to current prefixed locations."
		echo "Trying default locations, prefix [$str_defaultprefix]..."
	    fi
	fi
    fi # prefix

    set_prefix "${str_defaultprefix}"

    if can_write_to "${exec_dir}" "${wrapper_dir}" "${doc_dir}" "${share_dir}" "${plugin_dir}" "${man_dir}"
    then
	    # Default location success -> Recommend standard install
	if ver_bose; then echo "User \"${USERNAME}\" has write access to default locations. Prefix [${prefix}]"; fi
    else
	    # Default location failed -> Try other prefixes
	if ver_bose; then warn "User \"${USERNAME}\" does not have write access to default locations. Prefix [${prefix}]"; fi
	if test -z "${HOME}"
	then
	    warn " $str_progname: Enviroment variable \"${HOME}\" not set, user \"${USERNAME}\" has no homefolder?"
	    warn "Not trying locations with prefix [~/.]"
	else
	    if ver_bose; then warn "Trying prefix [${HOME}]..."; fi
	    set_prefix "${HOME}"

	    if can_write_to "${exec_dir}" "${wrapper_dir}" "${doc_dir}" "${share_dir}" "${plugin_dir}" "${man_dir}"
	    then
		# Prefix [~/.] success -> Recommend home install
		if ver_bose; then echo "User \"${USERNAME}\" has write access to locations with prefix [${prefix}]."; fi
	    fi
	fi
    fi
    confirm_paths
}


backup()
{
    # This function makes a backup of a file or directory to use in future rollback
    # This function is in development
    # 1 = file or directory
    # 2 = location in backup
    # 3 = folder to create

    debug_msg 0 "in backup()"

    rollback_dir="${share_dir}/uninst/rollback_${opera_version}"
    if test -f "$1" -o -d "$1"
    then
	if can_write_to "${rollback_dir}"
	then
	    test -d ${rollback_dir} || mkdir $mkdirv $mkdirp ${rollback_dir}
	    if test "$3"
	    then
		test -d ${rollback_dir}/$3 || mkdir $mkdirv $mkdirp ${rollback_dir}/$3
		location="$3/$2"
	    else
    		location="$2"
	    fi
	    if mv $mvv $mvf $1 ${rollback_dir}/${location} && ver_bose
	    then
		echo
		echo "Backup of:"
		echo " [$1] can be found at"
		echo " [${rollback_dir}/${location}]"
	    fi # ver_bose
	else warn "Can't make backup of [$1] for future rollback."
	fi
    else debug_msg 1 "[$1] does not exist"
    fi
}

generate_wrapper()
{

    # This function generates the wrapper script with correct opera path

    debug_msg 0 "in generate_wrapper()"

    case "${machine}:${os}" in
	x86:Linux|x86_64:Linux|x86:AnyBSD|x86_64:AnyBSD|x86:OpenBSD|x86:QNX)
	    wrapper_ibmjava="
	    IBMJava2-142/jre \\
	    IBMJava2-141/jre \\
	    IBMJava2-14/jre \\
	    IBMJava2-131/jre \\"
	    wrapper_sunjava_machine="i386"
	;;

	sparc:SunOS)
	    wrapper_sunjava_machine="sparc"
	;;

	x86:SunOS)
	    wrapper_sunjava_machine="i386"
	;;

	sparc:Linux)
	    wrapper_sunjava_machine="sparc"
	;;

	mips*:Linux)
	;;

	ppc:Linux|ppc64:Linux)
	    wrapper_ibmjava="
	    IBMJava2-ppc-14/jre \\
	    IBMJava2-ppc-131/jre \\"
	;;


	*:*)
		error 'os'
	;;
    esac
    wrapper_file="${wrapper_dir}/opera"

    wrapper_contain="#!/bin/sh

# Required for Session Management
case \$0 in /*) OPERA_SCRIPT_PATH=\$0;; *) OPERA_SCRIPT_PATH=`/bin/pwd`/\$0;; esac
export OPERA_SCRIPT_PATH

# Location of the Opera binaries
OPERA_BINARYDIR=${str_localdirexec}
export OPERA_BINARYDIR

# Parse commandline parameters
toset=
_QTSTYLE_FROM_CMDLINE_='NO'
for arg
do
  if test \"\$toset\"
  then
      eval \$toset=\"\$arg\"
      export \$toset
      toset=
  else
      case \$arg in
          --binarydir*|-binarydir*) toset=OPERA_BINARYDIR ;;
          --personaldir*|-personaldir*|--pd*|-pd*) toset=OPERA_PERSONALDIR ;;
          -style)
              _QTSTYLE_FROM_CMDLINE_='YES'
              ;;
      esac
  fi
done
test -z \"\$toset\" || die Missing parameter for \$arg

test \"\${_QTSTYLE_FROM_CMDLINE_}\" = 'NO' && test -f \"\$HOME/.qt/qtrc\" && _OPERA_QTSTYLE=\`sed -n 's/^style=//p' \$HOME/.qt/qtrc\` && test \"\$_OPERA_QTSTYLE\" && set -- \"\$@\" -style \"\$_OPERA_QTSTYLE\"


# Add ending path divider \"/\" if missing, so execution won't fail
if test \`echo \${OPERA_BINARYDIR} | sed -e 's/.*[^\/]$/NO/'\` = 'NO'; then
OPERA_BINARYDIR=\"\${OPERA_BINARYDIR}/\"
fi
if test ! -f \${OPERA_BINARYDIR}opera; then
    echo \"The Opera binary is not located at \\\"\${OPERA_BINARYDIR}opera\\\".\"
    echo \"Please modify the wrapper script at \\\"\${0}\\\".\"
    exit 1
elif test ! -x \"\${OPERA_BINARYDIR}opera\"; then
    echo \"You do not have execute rights on \\\"\${OPERA_BINARYDIR}opera\\\", please ask the sysadmin to chmod +x it.\"
    exit 1
fi

# Opera enviroment
if test \"\${OPERA_DIR}\" = '' ; then
  if test -d ${str_localdirshare} ; then
    OPERA_DIR=${str_localdirshare}
  else
    echo \"OPERA_DIR unset and not found at expected location (${str_localdirshare})\"
    exit 1
  fi
fi

OPERA_LD_PRELOAD=\"\${LD_PRELOAD}\"
export OPERA_LD_PRELOAD

# Native Java enviroment
for d in \"\$OPERA_PERSONALDIR\" \"\$HOME/.opera\"
do if test -f \"\$d/javapath.txt\"
   then
      INIJAVA=\`cat \"\$d/javapath.txt\"\`
      test -f \"\$INIJAVA/libjava.so\" || continue
      OPERA_JAVA_DIR=\"\$INIJAVA\"
      break
   fi
done

if test ! \"\$OPERA_JAVA_DIR\"
then for j in lib jre/lib
     do d=\"\$JAVA_HOME/\$j/$wrapper_sunjava_machine\"
        test -f \"\$d/libjava.so\" || continue
	OPERA_JAVA_DIR=\"\$d\"
	break
     done
fi

if test ! \"\${OPERA_JAVA_DIR}\"
then
    PREFIXES=\"
	/usr
	/usr/java
	/usr/lib
	/usr/local
	/opt\"

    for SUNJAVA in \\
	java-6-sun \\
	java-6-sun-1.6.0.00 \\
	java-1.5.0-sun \\
	java-1.5.0-sun-1.5.0.09 \\
	java-1.5.0-sun-1.5.0.09/jre \\
	java-1.5.0-sun-1.5.0.08 \\
	java-1.5.0-sun-1.5.0.08/jre \\
	java-1.5.0-sun-1.5.0.07 \\
	java-1.5.0-sun-1.5.0.07/jre \\
	java-1.5.0-sun-1.5.0.06 \\
	java-1.5.0-sun-1.5.0.06/jre \\
	jre1.5.0_06 \\
	jdk1.5.0_06/jre \\
	java-1.5.0-sun-1.5.0.05 \\
	java-1.5.0-sun-1.5.0.05/jre \\
	jre1.5.0_05 \\
	jdk1.5.0_05/jre \\
	java-1.5.0-sun-1.5.0.04 \\
	java-1.5.0-sun-1.5.0.04/jre \\
	jre1.5.0_04 \\
	jdk1.5.0_04/jre \\
	jre1.5.0_03 \\
	jdk1.5.0_03/jre \\
	jre1.5.0_02 \\
	jdk1.5.0_02/jre \\
	jre1.5.0_01 \\
	jdk1.5.0_01/jre \\
	jdk1.5.0/jre \\
	j2re1.4.2_06 \\
	j2sdk1.4.2_06/jre \\
	j2re1.4.2_04 \\
	j2sdk1.4.2_04/jre \\
	j2re1.4.2_03 \\
	j2sdk1.4.2_03/jre \\
	j2re1.4.2_02 \\
	j2sdk1.4.2_02/jre \\
	j2re1.4.2_01 \\
	j2sdk1.4.2_01/jre \\
	j2re1.4.2 \\
	j2sdk1.4.2/jre \\
	j2re1.4.1_01 \\
	j2re1.4.1 \\
	SUNJava2-1.4.1 \\
	BlackdownJava2-1.4.1/jre \\
	j2re1.4.0_01 \\
	j2sdk1.4.0_01/jre \\
	j2re1.4.0 \\
	jre1.4.0 \\
	j2se/1.4/jre \\
	j2se/1.3/jre \\
	j2se/jre \\
	jre1.3.1_15 \\
	jre1.3.1_04 \\
	jre1.3.1_02 \\
	jre1.3.1_01 \\
	j2re1.3.1 \\
	jre1.3.1 \\
	j2re1.3 \\
	j2se/1.3/jre \\
	SunJava2-1.3/jre \\
	java2re \\
	jdk1.2.2/jre \\
	jdk1.2/jre \\
	jre \\
	java \\
	jdk1.3.1/jre \\
	jdk1.4.2/jre \\
	jdk1.5.0/jre \\
	jdk1.6.0/jre \\
	diablo-jre1.5.0 \\
	diablo-jdk1.5.0/jre \\
	; do
	for PREFIX in \${PREFIXES}
	do d=\"\$PREFIX/\$SUNJAVA/lib/$wrapper_sunjava_machine\"
	   test -f \"\$d/libjava.so\" || continue
	   OPERA_JAVA_DIR=\"\$d\"
	   break
	done
	if test \"\${OPERA_JAVA_DIR}\"; then break; fi
    done"

if test -n "${wrapper_ibmjava}"; then
    wrapper_contain="${wrapper_contain}
    if test ! \"\${OPERA_JAVA_DIR}\"; then
	for IBMJAVA in \\${wrapper_ibmjava}
	    ; do
	    for PREFIX in \${PREFIXES}; do
		if test -f \"\${PREFIX}/\${IBMJAVA}/bin/libjava.so\"; then OPERA_JAVA_DIR=\"\${PREFIX}/\${IBMJAVA}/bin\" && break; fi
	    done
	if test \"\${OPERA_JAVA_DIR}\"; then break; fi
	done
    fi"
fi

    wrapper_contain="${wrapper_contain}
fi

if test \"\${OPERA_JAVA_DIR}\"; then
    LD_LIBRARY_PATH=\"\${OPERA_JAVA_DIR}:\${OPERA_JAVA_DIR}/native_threads:\${OPERA_JAVA_DIR}/client:\${OPERA_JAVA_DIR}/classic\${LD_LIBRARY_PATH:+:}\${LD_LIBRARY_PATH}\"
    export LD_LIBRARY_PATH OPERA_JAVA_DIR
fi

# Workarounds for the \"preloaded libXt\" problem.
LD_PRELOAD=\"libjvm.so:libawt.so:\${OPERA_LD_PRELOAD}\"
export LD_PRELOAD
# To disable the first workaround, comment the next line.
JAVA_WORKAROUND=\`\${OPERA_BINARYDIR}/works 2>/dev/null\`

if test \"\${JAVA_WORKAROUND}\" = 'works'; then
    OPERA_FORCE_JAVA_ENABLED=\"1\"
else
    LD_PRELOAD=\"libjava.so:\${LD_PRELOAD}\"
    # To disable the second workaround, comment the next line.
    IBMJAVA131_WORKAROUND=\`\${OPERA_BINARYDIR}/works 2>/dev/null\`
    if test \"\${IBMJAVA131_WORKAROUND}\" = 'works'; then
	OPERA_FORCE_JAVA_ENABLED=\"1\"
    else
	LD_PRELOAD=\"\${OPERA_LD_PRELOAD}\"
    fi
fi
export LD_PRELOAD OPERA_FORCE_JAVA_ENABLED

# Acrobat Reader
for BINDIR in \\
    /usr/local/Acrobat[45]/bin \\
    /usr/lib/Acrobat[45]/bin \\
    /usr/X11R6/lib/Acrobat[45]/bin \\
    /opt/Acrobat[45]/bin \\
    /usr/Acrobat[45]/bin \\
    ; do
    if test -d \${BINDIR} ; then PATH=\${PATH}:\${BINDIR}; fi
done

# Exporting the enviroment
export OPERA_DIR PATH

LD_LIBRARY_PATH=\"\${OPERA_BINARYDIR}\${LD_LIBRARY_PATH:+:}\${LD_LIBRARY_PATH}\"
export LD_LIBRARY_PATH

# Spellchecker needs to find libaspell.so.15
for LIBASPELL_DIR in \\
    /usr/local/lib \\
    /opkg/lib \\
; do
    if ls \$LIBASPELL_DIR/libaspell.so.1[5-9] >/dev/null 2>&1
    then LD_LIBRARY_PATH=\"\${LD_LIBRARY_PATH}:\${LIBASPELL_DIR}\"
    fi
done"

case "${os}" in
	AnyBSD|OpenBSD)
wrapper_contain="${wrapper_contain}

# Make sure the compat libraries are found
test -d /usr/local/lib/compat/ && LD_LIBRARY_PATH=\"\${LD_LIBRARY_PATH}:/usr/local/lib/compat/\"
"
	;;
    SunOS)
wrapper_contain="${wrapper_contain}

# Make sure libstdc++.so.6 is found on Solaris 10.
test -d /usr/sfw/lib/ && LD_LIBRARY_PATH=\"\${LD_LIBRARY_PATH}:/usr/sfw/lib/\"
"
	;;
esac

wrapper_contain="${wrapper_contain}

# Running Opera
exec \"\${OPERA_BINARYDIR}opera\" \"\$@\"
"

echo "${wrapper_contain}" > ${wrapper_file}
}

generate_opera_policy()
{
    policy_contain="
// Standard extensions get all permissions by default

grant codeBase \"file:\${java.home}/lib/ext/*\" {
	permission java.security.AllPermission;
};

// Opera package classes get all permissions
grant codebase \"file://${str_localdirshare}/java//opera.jar\" {
	permission java.security.AllPermission;
};

// default permissions granted to all domains

grant {
	// Allows any thread to stop itself using the java.lang.Thread.stop()
	// method that takes no argument.
	// Note that this permission is granted by default only to remain
	// backwards compatible.
	// It is strongly recommended that you either remove this permission
	// from this policy file or further restrict it to code sources
	// that you specify, because Thread.stop() is potentially unsafe.
	// See \"http://java.sun.com/notes\" for more information.
	permission java.lang.RuntimePermission \"stopThread\";

	// allows anyone to listen on un-privileged ports
	permission java.net.SocketPermission \"localhost:1024-\", \"listen\";

	// \"standard\" properies that can be read by anyone

	permission java.util.PropertyPermission \"java.version\", \"read\";
	permission java.util.PropertyPermission \"java.vendor\", \"read\";
	permission java.util.PropertyPermission \"java.vendor.url\", \"read\";
	permission java.util.PropertyPermission \"java.class.version\", \"read\";
	permission java.util.PropertyPermission \"os.name\", \"read\";
	permission java.util.PropertyPermission \"os.version\", \"read\";
	permission java.util.PropertyPermission \"os.arch\", \"read\";
	permission java.util.PropertyPermission \"file.separator\", \"read\";
	permission java.util.PropertyPermission \"path.separator\", \"read\";
	permission java.util.PropertyPermission \"line.separator\", \"read\";

	permission java.util.PropertyPermission \"java.specification.version\", \"read\";
	permission java.util.PropertyPermission \"java.specification.vendor\", \"read\";
	permission java.util.PropertyPermission \"java.specification.name\", \"read\";

	permission java.util.PropertyPermission \"java.vm.specification.version\", \"read\";
	permission java.util.PropertyPermission \"java.vm.specification.vendor\", \"read\";
	permission java.util.PropertyPermission \"java.vm.specification.name\", \"read\";
	permission java.util.PropertyPermission \"java.vm.version\", \"read\";
	permission java.util.PropertyPermission \"java.vm.vendor\", \"read\";
	permission java.util.PropertyPermission \"java.vm.name\", \"read\";
};
"
    echo "${policy_contain}" > "${share_dir}/java/opera.policy"
}

manifest_contains ()
{
    grep -q "$1"'$' Manifest.md5
}

manifest_path ()
{
    grep "$1"'$' Manifest.md5 | sed -e 's/[^ ]*  *//' -e "s:/$1"'$::'
}

manifest_select ()
{
    grep " $1/" Manifest.md5 | sed -e "s! $1/! !"
}

part_install()
{
    debug_msg 1 $3
    manifest_select "$1" | while read md5 file
    do
      if test -f "$1/$file"
      then rm -f "$2/$file"
      else warn "Missing file $f"
      fi
    done
    mkdir $mkdirv $mkdirp "$2"
    files="`manifest_select $1 | while read md5 file; do echo $file; done`"
    export files
    if [ "$files" ]
    then ( cd "$1"; tar cf - $files ) | ( cd "$2"; tar xof - )
    else warn "No files to copy from $1 to $2"; grep "$1" Manifest.md5 >&2
    fi
}

if type md5sum >/dev/null 2>&1
then md5check () { md5sum -c "$@"; }
elif type md5 >/dev/null 2>&1
then md5check () {
	cat "$@" | while read md5 file
	do got=`md5 -q $file`
	  if [ "$got" != "$md5" ]
	  then warn "$file FAILED md5 check: $got != $md5"
	  fi
	done
}
else md5check () { warn "No md5sum or md5 available with which to check manifest"; }
fi

run_install()
{
    # This function copies files to selected locations and

    debug_msg 0 "in run_install()"

    can_write_to ${exec_dir} || error access ${exec_dir}
    can_write_to ${wrapper_dir} || error access ${wrapper_dir}
    can_write_to ${doc_dir} || error access ${doc_dir}
    can_write_to ${man_dir} || error access ${man_dir}
    can_write_to ${share_dir} || error access ${share_dir}
    can_write_to ${plugin_dir} || error access ${plugin_dir}

    str_localdirexec="${exec_dir}"
    str_localdirshare="${share_dir}"
    str_localdirplugin="${plugin_dir}"

    chop "${OPERADESTDIR}" "str_localdirexec"
    chop "${OPERADESTDIR}" "str_localdirshare"
    chop "${OPERADESTDIR}" "str_localdirplugin"

    md5check Manifest.md5
    part_install "`manifest_path operapluginwrapper`" "$exec_dir" Binaries
    manifest_contains operapluginwrapper-native && part_install "`manifest_path operapluginwrapper-native`" "$exec_dir" Binaries
    manifest_contains operapluginwrapper-ia32-linux && part_install "`manifest_path operapluginwrapper-ia32-linux`" "$exec_dir" Binaries
    part_install "`manifest_path LICENSE`" "$doc_dir" Documentation
    part_install "`manifest_path man1/opera.1`" "$man_dir" "Manual page"

    share_src="`manifest_path 'html40_entities\.dtd'`"
    part_install "$share_src" "$share_dir" "Shared resources"
    # Leaving: usr/share/icons/* usr/share/pixmaps/* etc/* and the wrapper

    mkdir $mkdirv $mkdirp $plugin_dir/

    # Wrapper
    backup ${wrapper_dir}/opera opera
    debug_msg 1 "Wrapper"
    mkdir $mkdirv $mkdirp $wrapper_dir/

    #cp $cpv $cpf wrapper.sh $wrapper_dir/opera
    generate_wrapper
    chmod $chmodv 755 $wrapper_dir/opera

    if test -z "$OPERADESTDIR"
    then
	# System wide configuration files
	case $os in AnyBSD|OpenBSD) config_dir="/usr/local/etc";; *) config_dir="/etc";; esac
	# TODO: work out what's going on here and replace with something that sets OPERA_ROOTPREFS to where they went !
	if can_write_to "$config_dir"
	then
	    warn
	    warn "System wide configuration files:"
	    warn "  $config_dir/opera6rc"
	    warn "  $config_dir/opera6rc.fixed"
	    warn " would be ignored if installed with the prefix \"$prefix\"."
	    bool_config=1
	    if [ "$flag_mode" = '--interactive' ]
	    then con_firm "Do you want to install them in $config_dir" || bool_config=0
	    else warn "Installing in default location $config_dir instead."
	    fi

	    if [ $bool_config -eq 1 ]
	    then
		if [ -f "$config_dir/opera6rc" ]
		then
		    if [ "$flag_mode" = '--interactive' ] && con_firm "$config_dir/opera6rc exists: over-write it ?"
		    then
			backup $config_dir/opera6rc opera6rc config
			cp $cpv $cpf etc/opera6rc $config_dir
		    fi
		else cp $cpv $cpf etc/opera6rc $config_dir
		fi
		if [ -f "$config_dir/opera6rc.fixed" ]
		then
		    if [ "$flag_mode" = '--interactive' ] && con_firm "$config_dir/opera6rc.fixed exists: over-write it ?"
		    then
			backup $config_dir/opera6rc.fixed opera6rc.fixed config
			cp $cpv $cpf etc/opera6rc.fixed $config_dir
		    fi
		else cp $cpv $cpf etc/opera6rc.fixed $config_dir
		fi
	    fi
	else
	    warn
	    warn "User \"${USERNAME}\" does not have write access to $config_dir"
	    warn " System wide configuration files:"
	    warn "  $config_dir/opera6rc"
	    warn "  $config_dir/opera6rc.fixed"
	    warn " were not installed."
	fi

	# Shorcuts and Icons
	bool_icons=1 # install icons by default
	if test "${flag_mode}" = "--force" -o "${flag_mode}" = "--prefix="
	then
	    warn
	    warn "Shortcut icons would be ignored if installed with the prefix \"$prefix\"."
	    if [ "$flag_mode" = "--force" ]
	    then warn "Installing them in default locations."
	    else bool_icons=0; warn "Ignoring them; menus shall lack nice icons."
	    fi
	fi

	if test "$bool_icons" -ne 0
	then xdg
	fi

    fi # OPERADESTDIR

# Add uninstallation here

    if ver_bose
    then
	echo
	echo 'Installation completed. Enjoy !'
	if test "$flag_mode" = "--prefix="
	then
	    echo
	    echo "You've completed a prefixed installation."
	    echo
	else
	    if test "$flag_mode" = "--force"
	    then
		echo
		echo "You've completed a forced installation."
		echo
	    fi
	fi
	warn "Be sure to include $wrapper_dir in your PATH or invoke it as"
	warn "$wrapper_dir/opera or ./opera; and include $man_path in your MANPATH"
	warn "to make 'man opera' work, or invoke 'man -M $man_path opera'"
    fi # ver_bose
}

generate_wmconfig()
{
    # arg1 = location
    cat > "$1/opera" <<EOF && chmod $chmodv 644 "$1/opera"
opera name "Opera"
opera description "Opera Web Browser"
opera icon "opera.xpm"
opera mini-icon "opera.xpm"
opera exec "opera &"
opera group "Internet"
EOF
}

desktop_content()
{
    # arg1 = type
    echo '[Desktop Entry]'
    if test -z "$1"
    then cat <<EOF
Name=Opera
Exec=opera
Icon=opera.xpm
Terminal=false
EOF
    else
	if test "$1" = "xdg"
	then cat <<EOF
Version=1.0
TryExec=opera
EOF
	fi
	cat <<EOF
Encoding=UTF-8
Name=Opera
Name[af]=opera
Name[eo]=Opero
Name[zu]=I Opera
GenericName=Web browser
GenericName[bs]=Web preglednik
GenericName[de]=Web-Browser
GenericName[eo]=TTT-rigardilo
GenericName[es]=Navegador web
GenericName[et]=Veebibrauser
GenericName[eu]=Web arakatzailea
GenericName[fi]=WWW-selain
GenericName[fr]=Un navigateur web
GenericName[is]=Vafri
GenericName[it]=Browser Web
GenericName[nl]=webbrowser
GenericName[nn]=Nettlesar
GenericName[pt]=Navegador Web
GenericName[pt_BR]=Navegador
GenericName[ro]=Navigator de web
GenericName[sl]=Spletni brskalnik
GenericName[ven]=Buronza ya Webu
GenericName[xh]=Umkhangeli Zincwadi Zokubhaliweyo
GenericName[zu]=Umkhangeli zincwadi we Web
Exec=opera %u
Terminal=false
EOF

# Application is not a category, according to
# http://standards.freedesktop.org/menu-spec/menu-spec-latest.html
#
# but Chris included it anyway to fix
# http://bugs.gentoo.org/show_bug.cgi?id=90508
#
# Other possible categories:
# Email, Presentation, IRCClient, FileTransfer, P2P, News, WebDevelopment

	if test "$1" = "xdg"
	then cat <<EOF
Categories=Application;Qt;Network;WebBrowser;X-Ximian-Main;X-Ximian-Toplevel
Icon=opera.png
EOF
	else echo 'Icon=opera'
	fi
	echo 'MimeType=text/html;text/xml;application/xhtml+xml'
    fi
    cat <<EOF
Comment=Web Browser
Type=Application
EOF
}

generate_desktop()
{
    # arg1 = location
    # arg2 = type
    desktop_content $2 > "$1/opera.desktop" && chmod $chmodv 644 "$1/opera.desktop"
}

generate_mdk_menu()
{
    # arg1 = location
    cat <<EOF > $1/opera_menu_file && chmod $chmodv 644 $1/opera_menu_file
?package(opera):command="$wrapper_dir/opera" \\
icon="opera.png" \\
needs="X11" \\
section="Networking/WWW" \\
title="Opera" \\
longtitle="Opera Web Browser" \\
mimetypes="text/html,text/plain,text/vnd.csr,text/vnd.wap.wml,text/wml,text/xml,text/xhtml" \\
accept_url="true" \\
multiple_files="false"
EOF
}

icons()
{
    # This function searches for common icon paths.

    debug_msg 0 "in icons()"

    if test ! -d /usr/share/icons
    then
	if test -w /usr/share
	then
	    mkdir $mkdirv $mkdirp /usr/share/icons/
	    cp $cpv $share_src/pixmaps/opera.xpm /usr/share/icons/opera.xpm
	fi
    elif test -w /usr/share/icons
    then cp $cpv $share_src/pixmaps/opera.xpm /usr/share/icons/opera.xpm
    fi

    if test ! -d /usr/share/pixmaps
    then
	if test -w /usr/share
	then
	    mkdir $mkdirv $mkdirp /usr/share/pixmaps/
	    cp $cpv $share_src/pixmaps/opera.xpm /usr/share/pixmaps/opera.xpm
	fi
    elif test -w /usr/share/pixmaps/
    then cp $cpv $share_src/pixmaps/opera.xpm /usr/share/pixmaps/opera.xpm
    fi

    if test ! -d /etc/X11/wmconfig/
    then
	if test -w /etc/X11
	then
	    mkdir $mkdirv $mkdirp /etc/X11/wmconfig/
	    generate_wmconfig /etc/X11/wmconfig
	fi
    elif test -w /etc/X11/wmconfig/
    then generate_wmconfig /etc/X11/wmconfig
    fi

    if test -d /etc/X11/applnk/
    then
	if test ! -d /etc/X11/applnk/Internet/
	then
	    if test -w /etc/X11/applnk
	    then
		mkdir $mkdirv $mkdirp /etc/X11/applnk/Internet/
		generate_desktop /etc/X11/applnk/Internet
	    fi
	elif test -w /etc/X11/applnk/Internet
	then generate_desktop /etc/X11/applnk/Internet
	fi
    fi
}

gnome()
{
    # This function searches for common gnome icon paths.
    debug_msg 1 "in gnome()"

    if test -d /opt/gnome/
    then
	# /opt/gnome share
	if test -d /opt/gnome/share
	then
	    # /opt/gnome icon
	    if test ! -d /opt/gnome/share/pixmaps/
	    then
		if test -w /opt/gnome/share
		then
		    mkdir $mkdirv $mkdirp /opt/gnome/share/pixmaps/
		    cp $cpv $share_src/pixmaps/opera.xpm /opt/gnome/share/pixmaps/opera.xpm
		fi
	    elif test -w /opt/gnome/share/pixmaps
	    then cp $cpv $share_src/pixmaps/opera.xpm /opt/gnome/share/pixmaps/opera.xpm
	    fi
	    # end /opt/gnome icon

	    # /opt/gnome link
	    if test -d /opt/gnome/share/gnome/apps/
	    then
		if test -d /opt/gnome/share/gnome/apps/Internet/
		then
		    if test -w /opt/gnome/share/gnome/apps/Internet
		    then generate_desktop /opt/gnome/share/gnome/apps/Internet
		    fi
		elif test -d /opt/gnome/share/gnome/apps/Networking/WWW/
		then
		    if test -w /opt/gnome/share/gnome/apps/Networking/WWW
		    then generate_desktop /opt/gnome/share/gnome/apps/Networking/WWW
		    fi
		elif test -w /opt/gnome/share/gnome/apps
		then
		    mkdir $mkdirv $mkdirp /opt/gnome/share/gnome/apps/Internet/
		    generate_desktop /opt/gnome/share/gnome/apps/Internet
		fi
	    fi
	    # end /opt/gnome link
	fi
	# end /opt/gnome share

    elif test -d /usr/share/gnome/
    then
        # /usr/share/gnome icon
        if test ! -d /usr/share/gnome/pixmaps/
	then
	    if test -w /usr/share/gnome
	    then
		mkdir $mkdirv $mkdirp /usr/share/gnome/pixmaps/
		cp $cpv $share_src/pixmaps/opera.xpm /usr/share/gnome/pixmaps/opera.xpm
	    fi
	elif test -w /usr/share/gnome/pixmaps
	then cp $cpv $share_src/pixmaps/opera.xpm /usr/share/gnome/pixmaps/opera.xpm
	fi
	# end /usr/share/gnome icon

	# /usr/share/gnome link
	if test -d /usr/share/gnome/apps/
	then
	    if test -d /usr/share/gnome/apps/Internet/
	    then
		if test -w /usr/share/gnome/apps/Internet
		then generate_desktop /usr/share/gnome/apps/Internet
		fi
	    elif test -d /usr/share/gnome/apps/Networking/WWW/
	    then
		if test -w /usr/share/gnome/apps/Networking/WWW
		then generate_desktop /usr/share/gnome/apps/Networking/WWW
		fi
	    elif test -w /usr/share/gnome/apps
	    then
		mkdir $mkdirv $mkdirp /usr/share/gnome/apps/Internet/
		generate_desktop /usr/share/gnome/apps/Internet
	    fi
	fi
	# end /usr/share/gnome link
    fi
    # Add ximian here
}

kde()
{
    # This function searches for common kde2 and kde 3 icon paths.
    debug_msg 1 "in kde()"
    kroot=/opt/kde$1/share

    if test -d $kroot
    then
	DIR_HI=$kroot/icons/hicolor
	if test -d "$DIR_HI" -a -w "$DIR_HI"
	then
	    for res in 48x48 32x32 22x22
	    do
	      if test -d "$DIR_HI/$res/apps" -a -w "$DIR_HI/$res/apps"
	      then cp $cpv $share_src/icons/hicolor/$res/app/opera.png "$DIR_HI/$res/apps/opera.png"
	      fi
	    done
	fi

	DIR_LO=$kroot/icons/locolor
	if test -d $DIR_LO -a -w $DIR_LO
	then
	    for res in 32x32 22x22 16x16
	    do
	      if test -d $DIR_LO/$res/apps -a -w $DIR_LO/$res/apps
	      then cp $cpv $share_src/icons/hicolor/$res/opera.png $DIR_LO/$res/apps/opera.png
	      fi
	    done
	fi

	if test -d $kroot/applnk/
	then
	    if test ! -d $kroot/applnk/Internet/ -a -w $kroot/applnk
	    then mkdir $mkdirv $mkdirp $kroot/applnk/Internet/
	    fi
	    if test -w $kroot/applnk/Internet
	    then generate_desktop $kroot/applnk/Internet $1
	    fi
	fi
    fi

    if test -d /usr/share/applnk/Networking
    then
	if test ! -d /usr/share/applnk/Networking/WWW/ -a -w /usr/share/applnk/Networking
	then mkdir $mkdirv $mkdirp /usr/share/applnk/Networking/WWW/
	fi
	if test -w /usr/share/applnk/Networking/WWW
	then generate_desktop /usr/share/applnk/Networking/WWW $1
	fi
    fi
}

kde1()
{
    # This function searches for common kde1 icon paths.
    debug_msg 1 "in kde1()"

    if test -d /opt/kde/share
    then
	if test ! -d /opt/kde/share/icons/ -a -w /opt/kde/share
	then mkdir $mkdirv $mkdirp /opt/kde/share/icons/
	fi
	if test -w /opt/kde/share/icons
	then cp $cpv $share_src/pixmaps/opera.xpm /opt/kde/share/icons/opera.xpm
	fi

	if test ! -d /opt/kde/share/applnk/Internet/ -a -w /opt/kde/share/applnk
	then mkdir $mkdirv $mkdirp /opt/kde/share/applnk/Internet/
	fi
	if test -w /opt/kde/share/applnk/Internet
	then generate_desktop /opt/kde/share/applnk/Internet
	fi

    elif test -d /usr/share/applnk/Internet/ -a -w /usr/share/applnk/Internet
    then generate_desktop /usr/share/applnk/Internet
    fi
}

mandrake() # Now known as Mandriva
{
    if test -x /usr/bin/update-menus
    then
	test ! -d /usr/share/menu -a -w /usr/share && mkdir $mkdirv $mkdirp /usr/share/menu/
	test -d /usr/share/menu && generate_mdk_menu /usr/share/menu

	if [ -d /usr/lib/menu ]; then cp /usr/share/menu/opera /usr/lib/menu; fi

	test ! -d /usr/share/icons -a -w /usr/share && mkdir $mkdirv $mkdirp /usr/share/icons/
	test -d /usr/share/icons && cp $cpv usr/share/icons/hicolor/32x32/app/opera.png /usr/share/icons/opera.png

	test ! -d /usr/share/icons/mini -a -w /usr/share/icons && mkdir $mkdirv $mkdirp /usr/share/icons/mini/
	test -d /usr/share/icons/mini && cp $cpv usr/share/icons/hicolor/16x16/app/opera.png /usr/share/icons/mini/opera.png

	test ! -d /usr/share/icons/large -a -w /usr/share/icons && mkdir $mkdirv $mkdirp /usr/share/icons/large
	test -d /usr/share/icons/large && cp $cpv usr/share/icons/hicolor/48x48/app/opera.png /usr/share/icons/large/opera.png

	/usr/bin/update-menus || true
    fi
}

huntdirs()
{
    # $GNOME2PATH and $GNOMEPATH skipped (too few hits google site:gnome.org)
    # http://docs.kde.org/userguide/environment-variables.html
    echo ${GNOME2_PATH}:${KDEDIRS}:${GNOME_PATH}:${KDEDIR}:/usr:/opt/gnome:/opt/kde3 \
    | tr : '\012' | sed -e 's:$:'"/$1:"
}

pathdirs()
{
    # Places to look for executables, one per line:
    echo $PATH | tr : '\012'
    huntdirs bin
}

xdg()
{   # http://standards.freedesktop.org
    UDD=''
    for BIN_DIR in `pathdirs`; do
	test -x ${BIN_DIR}/update-desktop-database || continue
	UDD=${BIN_DIR}/update-desktop-database; break
    done

    # http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html
    if test "$UDD"; then
	for ICON_DIR in `echo ${XDG_DATA_DIRS}:/usr/local/share:/usr/share|tr : '\012'|sed -e '/^$/d;s:$:/icons/hicolor:'` /usr/share/pixmaps/hicolor
	do test -d ${ICON_DIR} && break
	done

	if   test ! -d ${ICON_DIR}
	then warn "Could not find icon installation directory, icons not installed."
	elif test ! -w ${ICON_DIR}
	then warn "Directory \"${ICON_DIR}\" not writable by user \"${USER}\", icons not installed."
	elif [ "`cd $ICON_DIR; /bin/pwd`" != "`cd usr/share/icons/hicolor; /bin/pwd`" ]
	then
	    for RESOLUTION in 48x48 32x32 22x22
	    do	TO_DIR=${ICON_DIR}/${RESOLUTION}/apps
		test -d $TO_DIR && test -w $TO_DIR && cp $cpv usr/share/icons/hicolor/$RESOLUTION/apps/opera.png $TO_DIR
	    done
	fi

	for SHORTCUT_DIR in ${XDG_DATA_HOME}/applications /usr/local/share/applications /usr/share/applications
	do test -d ${SHORTCUT_DIR} && break;
	done

	if   test ! -d ${SHORTCUT_DIR}; then warn "Could not find shortcut installation directory, desktop entry not installed."; return
	elif test ! -w ${SHORTCUT_DIR}; then warn "Directory \"${SHORTCUT_DIR}\" not writable by user \"${USER}\", desktop entry not installed."; return
	fi
	generate_desktop ${SHORTCUT_DIR} xdg
	${UDD}
    else
	icons
	gnome
	kde 3
	kde 2
	kde1
	mandrake
    fi
}

echo test | sed -n -e 's/test//' || error 'sed'

# AnyBSD systems don't have $USERNAME by default
if test -z "${USERNAME}" && test "${USER}"
then
    USERNAME="${USER}"
    debug_msg 0 "setting USERNAME to ${USER}"
fi

check_prefixes "$@"
select_installation_type
set_os_spesific
run_install
exit 0
