#!/bin/bash

echo OmniOS testing boostrap setup
echo
echo make sure, OmniOS gets installed: developer/gcc-3 or replacement
echo use omnios gcc4 as gcc-3 is no longer there at least in R151012
echo make sure, the directory you are in is writable to the user. or test-compile might fail with misleading errors...
#(needs a writable directory, does a compile testrun with /opt/*studio/bin/cc
echo
echo sleeping 5 seconds
sleep 5

##TODO## update to JDK 1.7 ! at least on the Solaris 11 and Solaris 12 variants

# changelog is at the end

##TODO## offer IPS link to Studio compiler, requires putting certificates into
#        extra publisher first
#http://www.oracle.com/technetwork/server-storage/solarisstudio/downloads/index.html
#https://pkg.oracle.com/solarisstudio/release

##TODO##
# add those IPS packages (check if on both, SX and OI needed it sunstudio12.2 is installed by the tarball)
# http://koberoi.com/2010/11/installing-oracle-solaris-studio-12-2-tarfile-on-solaris-11-express/
#     system/header
#     developer/java/jdk
#     system/library/math/header-math
#     developer/library/lint

function pauseshell {
[ -r /tmp/pauseshell ] || return
echo "pausing here: " $1
echo "enter exit 0  to continue or exit anynumber to exit bootstrap script"
bash
[ $? != 0 ] && exit $?
}


##TODO##
#if http_proxy is set, then do not getent hosts www.opensolaris.org
#  instead use "wget something" to detect if name resoultion/web-downloads are possible

#optional:
#UT_NO_USAGE_TRACKING 1
#SUNW_NO_UPDATE_NOTIFY 1

##TODO## re-order the first uses of SUPERRIGHTS / SUPERCMD to have that
#set proberly according to the platform. If possible, move e.g. /etc/release handling
#(zones where this file is missing) below the place where SUPERRIGHTS/SUPERCMD
#is evaluated.

#if [ "`ps -ofname -p $$|tail -1`" != "bash" ]
  #then
    #echo "This script currently *requires* that you invoke it with bash. Sorry!"
    #exit 23
#fi

export PKG_CLIENT_TIMEOUT=120
export PKG_ACCEPT_SHOW_LICENSE=""

#sane PATH (remember: with "su -" or "ssh" you can have again a polluted PATH 
#PATH=/usr/bin:/bin:/usr/sbin
PATH=/usr/gnu/bin:/usr/bin:/bin:/usr/sbin

#  
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright 2009-2010 Thomas Wagner
#
# CDDL HEADER END
#
# disclaimer: Use at your own risk! This is experimental code not intended for production use!
# it definitely alters your system and edits your configuration files without asking you for permission!
# use this script in a dedicated zone to be safe
# email: tom68@users.sf.net

# many thanks go to lewellyn, this script contains a lot of his suggestions and improvements 
# and he did testing and advertising and ...

VERSIONBOOTSTRAP=bootstrap-sfe-latest-20140319-2216
echo "Version: $VERSIONBOOTSTRAP"
uname -a

echo "setting locale to \"C\""
export LC_ALL=C
export LANG=C

export TARGETUSERNAME="$1"
echo "Checking for command-line-arguments.."
if [ -z "${TARGETUSERNAME}" ]
    then
    echo "Error: No username provided on the commandline! Please specify a valid"
    echo "username for which the devel-env for jucr/SFE should be set up"
    exit 1
fi

#check that ${TARGETUSERNAME} is not empty 
getent passwd "${TARGETUSERNAME}" &> /dev/null
if [ $? -eq 0 ]
    then 
    echo "Using username \"${TARGETUSERNAME}\" for the build environment."
  else
    echo "Error: Please specify a valid username for which the devel-env for"
    echo "jucr/SFE should be set up. The Username specified was: \"${TARGETUSERNAME}\""
    exit 1
fi

export USERHOMEDIR=`getent passwd ${TARGETUSERNAME} | cut -d ':' -f 6`

##TODO## warn if running user name is not the same then the username on the commandline


#to auto-accept the ssl certificates used with the first svn checkout there's no switch for.
#well, the echo "p" | svn co   in this scripcode at the end should help to auto-accept the cerificates ... (dangerous?)
SVNOPTIONS=""

#clean test farm .bash_profile to get a sane env. set this to "yes", anything other leaves this untouched
#CLEANBASHPROFILE=yes
CLEANBASHPROFILE=no

# end user adjustables

####===========================================================================================================

# check for id(1)
echo -n 'Checking for "id" command supporting the "-u" switch... '
found_id=0
for idpath in /usr/xpg4 /usr /usr/gnu; do
  [ $found_id -eq 0 ] && ${idpath}/bin/id -u > /dev/null 2>&1 && export IDCMD=${idpath}/bin/id && found_id=1
done
if [ ! -x $IDCMD ] 
  then
  echo ''
  echo 'There is no "id" command found which supports the switch "-u".'
  echo 'Please install package SUNWxcu4 or SUNWgnu-coreutils'
  exit 1
else
  echo "Found: $IDCMD"
fi

INVOKINGUSER="$($IDCMD -u -n)"
mkdir -p "/var/tmp/$INVOKINGUSER"
USERTEMP="/var/tmp/$INVOKINGUSER"

# check for ex(1)
echo -n 'Checking for "ex" command... '
found_ex=0
for expath in /usr/xpg6 /usr/xpg4 /usr/has /usr /usr/gnu; do
  [ $found_ex -eq 0 ] && [ -x ${expath}/bin/ex ] && echo :q | ${expath}/bin/ex -s -R /etc/passwd && export EXCMD=${expath}/bin/ex && found_ex=1
done
if [ ! -x $EXCMD ] 
  then
  echo ''
  echo 'There is no \"ex\" command found in the common places.'
  echo 'Please install package SUNWxcu4 or SUNWcs'
  exit 1
else
  echo "Found: $EXCMD"
fi

########################################################################
#                   check which OSDIST we are running on
#set default
export OSDIST="SXCE"

#check if we are on OS20[01][0-9]
#example: OS2009.06
##TODO## check if /etc/release was missing!  FILL OSDIST with a reasonable default!
# fix build zone missing the /etc/release file and estimate what would be written in there
# seen on test.opensolaris.org test "zone"
##TODO## improve: case switch based on the kernel-release running and estimate corresponding OS-Name
if [ -f /etc/release ] 
  then
   echo "Using existing file /etc/release"
  else
  $SUPERRIGHTS $EXCMD /etc/release << EOF
i
     OpenSolaris 2009.06
  faked /etc/release by bootstrap-sfe-* 
.
wq
EOF
#above not reliable, so set OSDIST anyway
OSDIST="OS2009.06"
fi #


#if we are on an IPS capable system and SUNWcs is installed, assume it is a real OS20nn and not SXCE or Solaris 10
##TODO## probably adjust this according to the OS Distro we are on, e.g. OpenIndiana
if [ -x /usr/bin/pkg ] && [ "$( /usr/bin/pkg info SUNWcs | grep "State: Installed" )" ]
  then
  [ -f /etc/release ] || $SUPERRIGHTS $EXCMD /etc/release << EOF
i
     OpenSolaris 2009.06
  faked /etc/release by bootstrap-sfe-* 
  pkg info checks for installed SUNWcs
.
:wq
EOF
#above not reliable, so set OSDIST anyway
OSDIST="OS2009.06"
fi #


#-----------------------------------------------------------------------
#-----------------------------------------------------------------------
#well, that was eventually a pre-view 2008.11 !!
#                          OpenSolaris 2008.11 snv_99 X86
#           Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
#                        Use is subject to license terms.
#                            Assembled 08 October 2008
#-----------------------------------------------------------------------
# snv_101 was the real 2008.11
#-----------------------------------------------------------------------
#                         OpenSolaris 2009.06 snv_111b X86
#           Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
#                        Use is subject to license terms.
#                              Assembled 07 May 2009
#-----------------------------------------------------------------------
#                       OpenSolaris Development snv_134 X86
#           Copyright 2010 Sun Microsystems, Inc.  All Rights Reserved.
#                        Use is subject to license terms.
#                             Assembled 01 March 2010
#-----------------------------------------------------------------------
#                      Oracle Solaris 11 Express snv_151a X86
#     Copyright (c) 2010, Oracle and/or its affiliates.  All rights reserved.
#                           Assembled 04 November 2010
#-----------------------------------------------------------------------
#                           Oracle Solaris 11 11/11 X86
#  Copyright (c) 1983, 2011, Oracle and/or its affiliates.  All rights reserved.
#                            Assembled 18 October 2011
#-----------------------------------------------------------------------
#                             Oracle Solaris 12.0 X86
#  Copyright (c) 1983, 2013, Oracle and/or its affiliates.  All rights reserved.
#                             Assembled nn MMMM cccc
#-----------------------------------------------------------------------

#set OSDIST to "SXCE" or "OS2009.06" ... "OS2010.nn"
#experimental OpenIndiana OI
#egrep "OpenSolaris .*(20[01][0-9].[0-9][0-9]|Development)" /etc/release && export OSDIST="OS`egrep "OpenSolaris 20[01][0-9].[0-9][0-9]" /etc/release | sed -e 's/.*OpenSolaris *//' -e 's/ .*//'`"
#good old IPS basedd OpenSolaris
echo "Checking for distribution ... "
#egrep "OpenSolaris .*(20[01][0-9].[0-9][0-9]|Development)" /etc/release 2>/dev/null && export OSDIST="OS2009.06"
egrep "Solaris .*(20[01][0-9].[0-9][0-9]|[0-9][0-9]\.[0-9]|Development)" /etc/release 2>/dev/null && export OSDIST="OS2009.06"
#note: above is only an estimation, see blow for build number checking to get more reliable detection of OS2009.06, OS2010.nn, ...

#below: only OpenIndiana style builds
#OpenIndiana
#                      OpenIndiana Development oi_147 X86
#        Copyright 2010 Oracle and/or its affiliates. All rights reserved.
#                        Use is subject to license terms.
#                           Assembled 14 September 2010
#example: OI2010.147
##TODO## make OI2010 automatic, so it automaticly moves to OI2011 next year
egrep "OpenIndiana Development" /etc/release 2>/dev/null && \
egrep "Assembled .* 2010" /etc/release 2>/dev/null && \
  export OSDIST="OI2010.$(egrep "OpenIndiana Development" /etc/release | sed -e "s/.*OpenIndiana Development oi_//" -e "s/ .*//" | head -1)"
#             OpenIndiana Development oi_151 X86 (powered by illumos)
#        Copyright 2011 Oracle and/or its affiliates. All rights reserved.
#                        Use is subject to license terms.
#                           Assembled 28 April 2011
#example: OI2011.151
egrep "OpenIndiana Development" /etc/release 2>/dev/null && \
egrep "Assembled .* 2011" /etc/release 2>/dev/null && \
  export OSDIST="OI2011.$(egrep "OpenIndiana Development" /etc/release | sed -e "s/.*OpenIndiana Development oi_//" -e "s/ .*//" | head -1)"

#      OpenIndiana Development oi_151.1.2 X86 (powered by illumos)
#         Copyright 2011 Oracle and/or its affiliates. All rights reserved.
#                         Use is subject to license terms.
#                           Assembled 09 February 2012
#example: OI2012.151.1.2
#   OpenIndiana Development oi_151.1.4 X86 (powered by illumos)
#        Copyright 2011 Oracle and/or its affiliates. All rights reserved.
#                        Use is subject to license terms.
#                           Assembled 22 April 2012
#example: OI2012.151.1.4
#   OpenIndiana Development oi_151.1.8 X86 (powered by illumos)
#        Copyright 2011 Oracle and/or its affiliates. All rights reserved.
#                        Use is subject to license terms.
#                           Assembled 20 July 2013
#example: OI2012.151.1.8
egrep "OpenIndiana Development" /etc/release 2>/dev/null && \
egrep "Assembled .* 201[23]" /etc/release 2>/dev/null && \
  export OSDIST="OI2012.$(egrep "OpenIndiana Development" /etc/release | sed -e "s/.*OpenIndiana Development oi_//" -e "s/ .*//" | head -1)"
#example: OMNIOS.151012
#  OmniOS v11 r151012
#  Copyright 2014 OmniTI Computer Consulting, Inc. All rights reserved.
#  Use is subject to license terms.
egrep "OmniOS" /etc/release 2>/dev/null && \
  export OSDIST="OMNIOS.$(egrep -o r[0-9][0-9][0-9][0-9][0-9][0-9] /etc/release | egrep -o [0-9][0-9][0-9][0-9][0-9][0-9])"

##TODO## might be that the new and much longer string triggers some effects, but this
#        is not very likely. OSDIST=OI2011.151 versus OSDIST=OI2012.151.1.2

#below: only OpenSolaris style builds
#note: value gets overwritten until no more checks left
#note: using "sed" to cut out letters from build-number on respin build, e.g. 151a -> 151
#be carefull, build number might contain letters from the re-spins! 111b, 151a and so on!
# Let's make sure we get something sane here...  OSDIST is currently something like OSDevelopment
#if [ \! "$OSDIST" == "SXCE" ]; then
#SunOS opensolaris 5.11 snv_99 i86pc i386 i86pc
if echo "$OSDIST" | grep "^OS20....." >/dev/null ; then
	if [ $(( $( uname -v | sed -e 's/[A-z]//g' -e 's/\..*//' | cut -f 2 -d _ ) >= 101 )) -eq 1 ]; then
		export OSDIST="OS2008.11" # People had better not be using these older builds...
	fi #>=101
#SunOS osol111 5.11 snv_111b i86pc i386 i86pc Solaris
	if [ $(( $( uname -v | sed -e 's/[A-z]//g' -e 's/\..*//' | cut -f 2 -d _ ) >= 111 )) -eq 1 ]; then
		export OSDIST="OS2009.06" # People had better not be using dev builds older...
                                          # lets say this is for up to build 134 (including), 
                                          # so exclude 134 from here and go to the next check
        fi # >=111
#re-visit the build number of the kernel - explicitly exclude /dev build 134 from here
#note: OS2010.02 and OS2010.03 are fake names, they did never exist in reality
#SunOS osol134 5.11 snv_134 i86pc i386 i86pc Solaris
	if [ $(( $( uname -v | sed -e 's/[A-z]//g' -e 's/\..*//' | cut -f 2 -d _ ) >= 133 )) -eq 1 ]; then
		export OSDIST="OS2010.02" # note: .02 is a fake number only
	fi # >=133 (133 had "The Great Rename", 134 with extra cream topping and some more renames )
	if [ $(( $( uname -v | sed -e 's/[A-z]//g' -e 's/\..*//' | cut -f 2 -d _ ) >= 134 )) -eq 1 ]; then
		export OSDIST="OS2010.03" # note: .03 is a fake number only
	fi # >=134 (133 had "The Great Rename", 134 with extra cream topping and some more renames )
#SunOS se151a 5.11 snv_151a i86pc i386 i86pc Solaris
	if [ $(( $( uname -v | sed -e 's/[A-z]//g' -e 's/\..*//' | cut -f 2 -d _ ) >= 151 )) -eq 1 ]; then
		export OSDIST="SX2010.11"
	fi # >=151
fi

#cat release
#                      Oracle Solaris 11 Express snv_156 X86
#     Copyright (c) 2011, Oracle and/or its affiliates.  All rights reserved.
#                           Assembled 30 December 2010
#

#Oracle Corporation      SunOS 5.11      11.0    November 2011
#tom@s11175:~$ uname -a
#SunOS s11175 5.11 11.0 i86pc i386 i86pc

#tom@s11175:~$ cat /etc/release 
#                           Oracle Solaris 11 11/11 X86
#  Copyright (c) 1983, 2011, Oracle and/or its affiliates.  All rights reserved.
#                            Assembled 18 October 2011
#
#SunOS s11175 5.11 11.0 i86pc i386 i86pc
	if uname -v | grep "^11\.[0-9]" ; then
		export OSDIST="SOL11.00"
                       #appromimation
                       BUILDNUM=175
                       PKG_ACCEPT_SHOW_LICENSE="--accept --license"
	fi # >= Solaris Kernel ID 11.0

#NOTE: OpenIndiana has the build number contained in the string, e.g. OI2010.147 OI2011.151

#-----------------------------------------------------------------------
#                           Oracle Solaris 11 11/11 X86
#  Copyright (c) 1983, 2011, Oracle and/or its affiliates.  All rights reserved.
#                            Assembled 18 October 2011
#-----------------------------------------------------------------------
#uname -v
#11.0
#                             Oracle Solaris 12.0 X86
#  Copyright (c) 1983, 2013, Oracle and/or its affiliates.  All rights reserved.
#                             Assembled nn MMMM cccc
#-----------------------------------------------------------------------
#uname -v
#s12_24
#Solaris 12 the same as Solaris 11 (for now)
	if uname -v | egrep "(^12\.[0-9])|(^s12_[0-9])" ; then
		export OSDIST="SOL12.00"
                       #appromimation
                       BUILDNUM=175
                       PKG_ACCEPT_SHOW_LICENSE="--accept --license"
	fi # >= Solaris Kernel ID 12.0


echo "Assuming this is a system of style: ${OSDIST}"

echo -n 'Checking/verifying uname -v build number... '
#note: this is for decisions early in this script
if [ -z $BUILDNUM ] 
   then
   BUILDNUM="$(egrep -o r[0-9][0-9][0-9] /etc/release | egrep -o [0-9][0-9][0-9])"
   #BUILDNUM="${BUILDNUM//[![:digit:]]}"
fi
echo "Assuming a kernel build number of: $BUILDNUM"

#you may override the above method by: example is to expoert the variable SUPERRIGHTS=ssh
#we need some default, especially for older builds
export SUPERRIGHTS=pfexec
export SUPERCMD=pfexec
#export SUPERRIGHTS=ssh
#export SUPERRIGHTS=sudo
#export SUPERRIGHTS="" for systems where "sudo bash" + root_password is needed to get rights
#NOT IMPLEMENTED export SUPERRIGHTS=su
  
# offset to the place where the svn repositories are stored (svn are checked out only if such a target directory does not already exist)
# ../place/it/relative/here  or /storeplace/absolute/here
# /toreplace/absolute/${TARGETUSERNAME}/development/
# default is "${USERHOMEDIR}/" which results in ${USERHOMEDIR}/spec-files-jucr and ${USERHOMEDIR}/spec-files-extra
SVNTARGETBASEPATH="${USERHOMEDIR}"


# this is intended for SXCE or Solaris 10. For new Solaris-style Distros there is
# the CCOMPILERPATHLIST below
# where lives your SunStudio C/C++-Compiler? Here you may override the default
# or leave this empty/unset and the script will try to find SunStudio(Express)
#CCOMPILERPATH=/opt/SUNWspro/bin/cc
#CCOMPILERPATH=

# on Solaris-style distros we search a path list for a SunStudio C/C++-Compiler (never gcc!)
CCOMPILERPATHLIST="/opt/solarisstudio12.3 /opt/solarisstudio12* /opt/solstudio12.2 /opt/sunstudio12.2 /opt/sunstudio12u2 /opt/sunstudio12.1 /opt/sunstudio12u1 /opt/sunstudio* /opt/SUNWspro"

# if we want to compiler installed from a tarball, then watch out those directories for
# files matching the pattern, choose the sort-order to select highest numbers in case
# of multiple matches. e.g. 12.1 12.2 12.3 present, then choose 12.3
#CCOMPILERTARBALLDIR="./ /resource/SOURCES"
CCOMPILERTARBALLDIR="`pwd` /resource/SOURCES"
#selected is the highest number available
CCOMPILERTARBALLPATTERN="SolarisStudio12.[123]-solaris-(x86|sparc)-bin(.tar|).bz2"

#*OR* export before running the script this variable in your shell:
#export CCOMPILERTARBALLFILE="/here/is/the/compilertarball"
#accepted files are pure tarballs containing SolarisStudio*/solstudio12.* directory

#where the sources, build scratch, pkgs, spkgs should go. default is: PACKAGESDIR=${USERHOMEDIR}/packages
PACKAGESDIR=${USERHOMEDIR}/packages

########################################################################
# it's unlikely that you have to change the settings below:
#OS2009.06
PACKAGESADDIPS="text/gnu-patch web/wget archiver/gnu-tar
                  package/svr4 omniti/perl/xml-parser
                  developer/build/gnu-make developer/build/automake
                  text/gnu-sed text/gawk text/gnu-diffutils file/gnu-coreutils
                  text/gnu-gettext
                  text/gnu-grep file/gnu-findutils developer/macro/gnu-m4
                  omniti/developer/library/boost/boost-source compress/unzip
               "
#PACKAGESADDIPS="SUNWgpch SUNWwget SUNWgtar 
#                  SUNWxorg-headers SUNWpkgcmds SUNWperl-xml-parser 
#                  SUNWgmake SUNWgnu-automake-110 SUNWgnome-doc-utils 
#                  SUNWgsed SUNWgawk SUNWgnu-diffutils SUNWgnu-coreutils 
#                  SUNWgnome-base-libs SUNWgnome-common-devel SUNWgnu-gettext
#                  SUNWggrp SUNWgnu-findutils SUNWgnu-coreutils SUNWgm4
#                  SUNWdoxygen SUNWunzip
#               "
#more packages cbe-install loves SUNWxcu4 with /usr/xpg4/bin/id
PACKAGESADDIPS="$PACKAGESADDIPS system/xopen/xcu4 system/xopen/xcu6
               "
#PACKAGESADDIPS="$PACKAGESADDIPS SUNWxcu4 SUNWxcu6 SUNWgnome-xml
#               "
#more packages for S11 and OI (needed for CBE)
PACKAGESADDIPS="$PACKAGESADDIPS system/library/processor system/library/platform
               "
#PACKAGESADDIPS="$PACKAGESADDIPS SUNWcar SUNWkvm
#               "

#more suggestions from email 17 Jul 2009 13:24:08 +0100 From: Christian Kelly <Christian.Kelly@Sun.COM>
PACKAGESADDIPS="$PACKAGESADDIPS library/python-2/python-extra-26 omniti/runtime/tcl-8 
                  developer/library/lint system/file-system/autofs shell/bash compress/bzip2
               "
#PACKAGESADDIPS="$PACKAGESADDIPS SUNWPython SUNWTcl SUNWTiff SUNWTk SUNWadmap 
#                  SUNWadmlib-sysid SUNWadmr SUNWarc SUNWatfs SUNWbash SUNWbzip
#               "

# Stuff that's in ss-dev
##PARKING -> moved to allowed-to-fail
##PACKAGESADDIPS="$PACKAGESADDIPS SUNWj6dmo SUNWj6cfg SUNWj6rt SUNWj6rtx
##                  SUNWj6man SUNWj6dvx SUNWj6dev SUNWj6dmx SUNWbtool
##               "

#just in case it is missing (jdscbe has old svn w/ broken libdb.so, desktop-cbe has no svn at all)
PACKAGESADDIPS="$PACKAGESADDIPS omniti/developer/versioning/subversion
               developer/versioning/mercurial
               "
#PACKAGESADDIPS="$PACKAGESADDIPS SUNWsvn 
#               SUNWmercurial
#               "

#SUNWaconf removed from the presence checks in desktop-cbe, so make sure it is installed here
PACKAGESADDIPS="$PACKAGESADDIPS developer/build/autoconf developer/parser/bison developer/lexer/flex developer/build/libtool
               "
#PACKAGESADDIPS="$PACKAGESADDIPS SUNWaconf SUNWbison SUNWflexlex SUNWlibtool
#               "

# those package are allowed to fail the install, newer osbuilds usually do incorportate the files in other packages
#>=130 SUNWsfwhea is gone >=133 SUNWhea is gone
PACKAGESADDIPSALLOWEDFAIL="SUNWhea SUNWsfwhea
                           network/ftp packages/SUNWbip
                          "

#Workaround: on OI151devA it knows about e.g. SUNWj6rt but it fails, why?
PACKAGESADDIPSALLOWEDFAIL="$PACKAGESADDIPSALLOWEDFAIL
                           SUNWj6dmo SUNWj6cfg runtime/java SUNWj6rtx
                           SUNWj6man SUNWj6dvx developer/java/jdk SUNWj6dmx developer/object-file
                          "
#looks like gcc-3 compiler is not longer part of the OI151a (/dev) default installation
#looks like gcc-3 compiler is not longer part of the Solaris 11 default installation
if echo ${OSDIST} | egrep "OI201.|SX201.|SOL11\.|SOL12\.|OMNIOS" > /dev/null ; then
PACKAGESADDIPSALLOWEDFAIL="$PACKAGESADDIPSALLOWEDFAIL
                          developer/gcc-3
                          pkgbuild
                          network/rsync
                          "
fi

#newer OSDISTRO doN't have /usr/gnu/bin in PATH! so gnu m4 in /usr/gnu/bin/m4 not found by CBE install checks
###it looks like oi151a8 (or similar) don't have SUNW gnu m4 installed, or can't
###be found by old legacy name SUNWgm4. Just try it by the IPS package name again:
##PACKAGESADDIPSALLOWEDFAIL="$PACKAGESADDIPSALLOWEDFAIL
                          ##developer/macro/gnu-m4
                          ##"

# These are in gcc-dev
#PACKAGESADDIPS="$PACKAGESADDIPS SUNWgmake SUNWgnu-automake-110 SUNWsvn
#               "

# build specific package names 
# for obsolete SUNWhea (inclue files .h) into other base packages"
if [ $(( $BUILDNUM >= 144 )) -eq 1 ]; then
#PACKAGESADDIPS="$PACKAGESADDIPS pkg://solaris/compatibility/packages/SUNWxwinc doesn't work on OI!
#PACKAGESADDIPS="$PACKAGESADDIPS pkg://compatibility/packages/SUNWxwinc
PACKAGESADDIPS="$PACKAGESADDIPS
               " 
#PACKAGESADDIPS="$PACKAGESADDIPS packages/SUNWxwinc
#               " 
else
#adding ss-dev is a try, we just don't want on newer systems the old sunstudioexpress compiler pulled in by "require"
#see  pkg contents -m -r ss-dev   -->> depend fmri=sunstudioexpress@0.2009.3-0.111 type=require
PACKAGESADDIPS="$PACKAGESADDIPS SUNWxwinc
               ss-dev
               " 
fi # >=133

#/usr/bin/as moved from make to assembler (SOL11 example)
#developer/build/make@0.5.11,5.11-0.167   still the case for OmniOS! need a rule below to address OmniOS
#developer/assembler@0.5.11,5.11-0.168   S11 >= 168 and S12
#NOT CHECKED: openindiana version
if echo ${OSDIST} | egrep "OI201.|SOL11\." && [ $(( $BUILDNUM < 168 )) -eq 1 ]; then
PACKAGESADDIPS="$PACKAGESADDIPS
                 developer/build/make
               "
else
#S11 >= 168, S12 all
PACKAGESADDIPS="$PACKAGESADDIPS
                 system/header
               "
fi # >=

#OmniOS
#replacement for missing gcc-3 (arround >= R151012) we take developer/gcc48 and make symlinks into /usr/sfw/bin
if echo ${OSDIST} | egrep "OMNIOS" > /dev/null ; then
PACKAGESADDIPS="$PACKAGESADDIPS
                 developer/gcc48
               "
#no, try SFEgcc with studio, then SFEgcc delivers symliks to /usr/sfw/bin/ for us
#disabled RUNOM201X_GCC3_SYMLINKS=yes
fi # >=

#COMPILERPACKAGEIPS="pkg:/developer/sunstudioexpress"
COMPILERPACKAGEIPS="pkg:/developer/sunstudio12u1"

#unused: (Full-install of SXCE is assumed!)
PACKAGESADDSXCE=""

#currently unused:
COMPILERPACKAGESXCE="SUNWspro"

# Common Build Environment
#normal ${HOSTTYPE} of type sparc or i386
#experimental is cbe 1.7.x (might become stable some day)
#note: HOSTTYPE is set from calling shell
#rework download-link  i386 -> x86
CBEURL001007000="http://dlc.sun.com/osol/jds/downloads/cbe/test/desktop-cbe-1.7.0-rc1-${HOSTTYPE}.tar.bz2"
CBEURL001007000="`echo $CBEURL001007000 | sed -e 's/-i386/-x86/'`"

# use stable cbe 1.6.2
CBEURL001006002="http://dlc.sun.com/osol/jds/downloads/cbe/jds-cbe-1.6.2-${HOSTTYPE}.tar.bz2"

# use newer cbe for OI and Solaris Express 11 builds
#http://dlc.sun.com/osol/jds/downloads/cbe/test/desktop-cbe-mini-1.8.0.tar.bz2
#CBEURL001008000=http://dlc.sun.com/osol/jds/downloads/cbe/test/desktop-cbe-mini-1.8.0.tar.bz2
CBEURL001008000="http://sourceforge.jp/frs/redir.php?m=jaist&f=%2Fjposug%2F62461%2Fdesktop-cbe-mini-1.8.0.tar.bz2"

###SET DEFAULT (note: if OSDISTRO is detected as OI or Solaris Express 11 
###then the second vaiable will be used
CBEURL=${CBEURL001006002}
#CBEURL=${CBEURL001007000}
#use 1.6.2           CBEURL2=${CBEURL001006002}
#or use 1.7.0-rc1    CBEURL2=${CBEURL001007000}
#or use 1.8 (might not work with this installscript)   CBEURL2=${CBEURL001007000}
#CBEURL2 is intended for more recent osbuilds, replaces old CBEURL
CBEURL2=${CBEURL001008000}
#CBEURL2=${CBEURL001007000}
#CBEURL2=${CBEURL001006002}

# Add newer pkgbuild version
#updated pkgbuild normal
# PKGBUILDURL="http://prdownloads.sourceforge.net/pkgbuild/pkgbuild-1.3.3.tar.bz2?download"

#updated pkgbuild experimental
#PKGBUILDURL="http://prdownloads.sourceforge.net/pkgbuild/pkgbuild-1.3.103.tar.bz2?download"
#PKGBUILDURL="http://prdownloads.sourceforge.net/pkgbuild/pkgbuild-1.3.103.tar.bz2"
PKGBUILDURL="http://downloads.sourceforge.net/project/pkgbuild/pkgbuild/1.3.104/pkgbuild-1.3.104.tar.bz2"
#PKGBUILDURL="http://downloads.sourceforge.net/project/pkgbuild/pkgbuild/1.3.105/pkgbuild-1.3.105.tar.bz2"



# pkgbuild from cvs repository!
# cvs -z3 -d:pserver:anonymous@pkgbuild.cvs.sourceforge.net:/cvsroot/pkgbuild co -r ips2 pkgbuild

#check-deps.pl fetch URL
CHECKDEPSURL="http://src.opensolaris.org/source/raw/sfwnv/usr/src/tools/check-deps.pl"



#repositories to be checked out (spec-files-extra, spec-files-jucr)
# not mentioned are: spec-files-other, spec-files

#check out this repository with this command:
###
###
# the "echo p" puts the answer for permaently accepting the fingerprints
###SVNCHECKOUT="echo p | svn $SVNOPTIONS co https://pkgbuild.svn.sourceforge.net/svnroot/pkgbuild/spec-files-extra/trunk ${SVNTARGETBASEPATH}/spec-files-extra/"
#SVNCHECKOUT="echo p | svn $SVNOPTIONS co https://pkgbuild.svn.sourceforge.net/svnroot/pkgbuild/spec-files-extra/trunk ${SVNTARGETBASEPATH}/spec-files-extra/"
SVNCHECKOUT="echo p | /opt/omni/bin/svn $SVNOPTIONS co https://svn.code.sf.net/p/pkgbuild/code/spec-files-extra/trunk ${SVNTARGETBASEPATH}/spec-files-extra/"
###
###
### others...
###

#we still have no automatic accept for the ssh keys here
###JUCRSVNCHECKOUT="svn $SVNOPTIONS co svn+ssh://anon@svn.opensolaris.org/svn/sourcejuicer/spec-files-jucr/trunk ${SVNTARGETBASEPATH}/spec-files-jucr"
#alternative to echo yes: create file and supply -F config.nostrict  with content StrictHostKeyChecking no
#JUCRSVNCHECKOUT="echo yes | svn $SVNOPTIONS co svn+ssh://anon@svn.opensolaris.org/svn/sourcejuicer/spec-files-jucr/trunk ${SVNTARGETBASEPATH}/spec-files-jucr"
#unfortunatly the repository is gone, one day we might have an archive online just to get the vaulable spec files recycled on eday
JUCRSVNCHECKOUT="/bin/true"

#checkout the GNOME desktop stuff from java.net, spec-files is known as
#kind of the father of spec-files-extra

SPECFILESCHECKOUT="hg clone https://hg.java.net/hg/solaris-desktop~spec-files ${SVNTARGETBASEPATH}/spec-files"



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


#fix different flavours of IPS based Distros to have a resonable OS20nn.nn numbering
##TODO## *needs* improvement e.g. "OpenSolaris Development snv_118 X86" -> OS2010.02   "OpenSolaris 2009.06 snv_111b X86"  -> OS2009.06
#make a default if string is only "OS"
echo $OSDIST | egrep "^OS$" >/dev/null && OSDIST=OS2009.06

# hands-off installs need paswords to be stored temprarily.
# at least TRY to remove any passwords from previous runs
##TODO## make storage more safe
rm -f /tmp/HDjaHAUEdkjsj36aAHS_sfescmd_jskdhsks7238s.* 2>/dev/null
trap "rm -f /tmp/HDjaHAUEdkjsj36aAHS_sfescmd_jskdhsks7238s.$$" SIGINT SIGTERM

#older builds can elevate permissions easily by just prefixing with "pfexec"
#see next block below, newer builds can't pfexec any more, they use sudo
#we bail out if we can't find sudo on such a new system
if echo ${OSDIST} | egrep "OS20[01][0-9].[0-9n][0-9n]" > /dev/null
   then #we are on OS2008.11, 2009.06, 2010.02, 2010.03 or similar
   echo "Changing to \"pfexec\" to elevate permissions, since this is OS2008/OS2009/OS2010"
   export SUPERRIGHTS=pfexec
   export SUPERCMD=pfexec
   /usr/bin/profiles ${USER} | grep "Primary Administrator" > /dev/null
   if [ $? != 0 ]; then
	echo ""
	echo "ERROR!"
	echo "======"
	echo ""
	echo "You must have the Primary Administrator role for your current"
	echo "user account for this script to work properly."
	echo ""
	echo "Please add this role to your user, logout and login again, then try again!"
	echo ""
	exit 7
   fi
fi


if echo ${OSDIST} | egrep "SOL12\." > /dev/null && [ ! -f /tmp/nopublishercheck ]
   then
 # http://pkg.oracle.com/solaris/release/
 # http://ipkg.us.oracle.com/solaris12/dev/
   if pkg publisher | grep "http://pkg.oracle.com/solaris/release/" 
      then
      echo "please set the publisher to the internal publisher on this distro >${OSDIST}<."
      echo "to override this check, use touch /tmp/nopublishercheck"
      echo ""
      echo "  sudo pkg set-publisher -G  http://pkg.oracle.com/solaris/release/ -g http://ipkg.us.oracle.com/solaris12/dev/
 solaris"
      echo ""
      exit 1
      fi #end yes, wrong publisher found
   fi #end check for S12 and internal publisher

#Solaris 11 Express and OpenIndiana (to be verified)
#do not longer give root level rights if "pfexec" is used.
#for security there is "sudo" to be used wich at least once asks
#for the password of the user allowed to run sudo
if echo ${OSDIST} | egrep "SX20[01][0-9].[0-9n][0-9n]|OI201[012].[0-9][0-9][0-9]|SOL11\.|SOL12\.|OMNIOS" > /dev/null
   then #we are on Solaris 11 Express (here: OS2010...) or OpenIndiana
   echo "Changing to \"sudo\" to elevate permissions, since this is SX2010/OI2010/OI2011/SOL11/SOL12"
   export SUPERRIGHTS=sudo
   if [ ! -x /usr/bin/sudo ] 
     then
     echo ""
     echo "   ERROR. /usr/bin/sudo is not found working. You *need* sudo on this"
     echo "   platform to get the permissions needed for this bootstrap script"
     echo ""
     echo "   please install sudo with this command:"
     echo "     pfexec pkg install sudo"
     echo ""
     echo "   then check sudo for correct setup by running this and reading the output:"
     echo ""
     echo "     sudo id                      (you will be prompted for the regular"
     echo "                                   user-password)"
     echo "     uid=0(root) gid=0(root)      (this is the output if sudo works correctly"
     echo "                                   else, please repair sudo. We need for the  "
     echo "                                   user these settings: `logname` ALL=(ALL) ALL"
     exit 8
   fi
   echo ""
   echo ""
   echo "NOTE:"
   echo "====="
   echo ""
   echo "Unless otherwise directed, this script prompts for *YOUR* password."
   echo ""
   echo ""
   echo "For elevating permisisons we use \"sudo\"\c"
[ -z ""${INVOKERPW} ] && echo ", please enter your regular user password below:"
   export SUDO_PROMPT="[bootstrap-sfe] YOUR password:"
[ -z ""${INVOKERPW} ] && read -s -r -p "${SUDO_PROMPT}" INVOKERPW
   echo '#!/bin/sh' > /tmp/HDjaHAUEdkjsj36aAHS_sfescmd_jskdhsks7238s.$$
   # Believe it or not, this is the easiest way to deal with "complex" passwords
   SUDO_PROMPT='(using sudo) '
   printf "echo \$'%q\\\n' | sudo -E -S \"\$@\"" "${INVOKERPW}" >> /tmp/HDjaHAUEdkjsj36aAHS_sfescmd_jskdhsks7238s.$$
   chmod 500 /tmp/HDjaHAUEdkjsj36aAHS_sfescmd_jskdhsks7238s.$$
   unset INVOKERPW
   export SUPERCMD="/tmp/HDjaHAUEdkjsj36aAHS_sfescmd_jskdhsks7238s.$$"
   echo ""
##TODO##
#place a first test of this SUPERCMD right here, if it fails tell the user that it exits here and he should restart the bootstrap script for retry"
   echo ""
fi

#paused, mixed situation with root as a role or not and zone and.... just used pfexec for now
#if echo ${OSDIST} | egrep "OI201[012].[0-9][0-9][0-9]" > /dev/null
   #then
   #echo "Resetting, no elevate permissions needed, we install as root-user"
   #echo "on OpenIndiana and recent Solaris Express 11 builds"
   #export SUPERRIGHTS=""
#fi

#work around script blaming they run as "root" and shouldn't - we switch then to the intended target username to let him do the work
#beware, it does a complete "su -" wich eliminates the whole envrionment and PATH and workind-directory ...
if [ "$( $IDCMD  -u -n | grep -w "${TARGETUSERNAME}" )" ]
  then
  #already running as the target/build user
  export USESU=""
else
  export USESU="su - ${TARGETUSERNAME} -c "
  #test if "pfexec" helps to run su without asking for a password
  #$USESU ls < /dev/null && export USESU="/usr/bin/pfexec $USESU"
  echo "Testing for su command. If you get a password prompt, press ENTER on your"
  echo " keyboard to continue ..."
##TODO## might print error on OI147 but continue running:  Zeile 139: [: -eq: Einstelliger (unärer) Operator erwartet.
  #older if [ $(${SUPERRIGHTS} /usr/bin/su ${TARGETUSERNAME} -c '/usr/bin/true;echo $?') -eq 0 ]; then
  #older   export USESU="${SUPERRIGHTS} ${USESU}"
  if [ $(${SUPERCMD} /usr/bin/su ${TARGETUSERNAME} -c '/usr/bin/true;echo $?') -eq 0 ]; then
    export USESU="${SUPERCMD} ${USESU}"
  fi
fi

do_su() {
  if [ -z "$USESU" ]; then
    echo "You're installing for yourself or as real root user,"
    echo "no need to prompt for password."
    echo "$@"
    sh -c "$@"
  else
    $USESU "$@"
  fi
}

#set the compiler non-smart if not already defined by the user and
#decide compiler depending on $OSDIST
if [ -z "$CCOMPILERPATH" ]
  then
    #default is same path as in SXCE, then see alternatives
    CCOMPILERPATH=/opt/SUNWspro/bin/cc
    #note: newer distros use CCOMPILERPATHLIST and ignore $CCOMPILERPATH
fi          #if "$CCOMPILERPATH" == ""
     


getent passwd "${TARGETUSERNAME}" &> /dev/null
if [ $? -eq 0 ]
    then
    echo "Checking for assigned User-Profile \"Software Installation\"..."
 else
    echo "Username specified (${TARGETUSERNAME}) is not found in /etc/passwd"
    exit 1
fi

echo "Checking for existing profile \"Software Installation\"..."
PROFILEREGEX="(Software Installation|Primary Administrator)"
#for now only OI need a different setup (including Software Installation)
echo ${OSDIST} | egrep "OI201[012].[0-9][0-9][0-9]" > /dev/null && PROFILEREGEX="(Software Installation)"

#PROFILECHECK="$(/usr/bin/profiles ${TARGETUSERNAME} | egrep "(Software Installation|Primary Administrator)")"
PROFILECHECK="$(/usr/bin/profiles ${TARGETUSERNAME} | egrep "$PROFILEREGEX"  )"
if [ $? == 0 ]
    then
    echo "Username $TARGETUSERNAME already owns the profile(s): (display is filtered)"
    echo $PROFILECHECK
    echo "You are a good one. Unbelievable rights already assigned."
    echo ""
 else
    echo "OLD: Profiles Settings:"
    echo "======================="
    /usr/bin/profiles "$TARGETUSERNAME"
    echo "======================="
    echo "Setting profile to \"Software Installation\" for $TARGETUSERNAME ..."

    echo "add the profile \"Software Installation\" to your login-user (${TARGETUSERNAME})"
    echo ""
    #echo "*****************"
    #echo "READ: you will be prompted for the root password (defaults initially to the"
    #echo "password of the first user on test.opensolaris.org *or* it is the password"
    #echo "you assigned e.g. during initial installation of your own OS copy)"
    #echo ""
    OLDPROFILE=`grep "^$TARGETUSERNAME:" /etc/user_attr | head -1 | sed -e 's/^.*[;:]profiles=//' -e 's/[;$].*//'`
    #HACK# only for OI first, eventually needed for Solaris Express 11 as well
    if echo ${OSDIST} | egrep "OS20[01][0-9].[0-9n][0-9n]|SX20[01][0-9].[0-9n][0-9n]|OI201[012].[0-9][0-9][0-9]|SOL11\.|SOL12\.|OMNIOS" > /dev/null
    then
    OLDPROFILE=`grep "^$TARGETUSERNAME:" /etc/user_attr | head -1 | grep -w "profiles=" | sed -e 's/.*\(profiles=\)/\1/' -e 's/profiles=//' -e 's/;.*$//'`
    fi
    #HACK#
    [ -z $OLDPROFILE"" ] || export SEPARATOR=","
    case $SUPERRIGHTS in
    # check comments below with a Solaris 10 and a SXCE - might be different..to a IPS osolified OS
    # XXX: Only ssh works properly. If you can assume root with pfexec, you don't
    #      need to do this. If not, you probably can't su either...
     "pfexec"|"sudo") #tested
        ${SUPERCMD} /usr/sbin/usermod -P "$OLDPROFILE""$SEPARATOR""Software Installation" "$TARGETUSERNAME"
#Hack
if [ $? != 0 ] ; then
echo "usermod failed. you probably should run \"${SUPERCMD} bash\" and then re-run the same script as root user"
fi
#End Hack
        ;;
     "ssh")    #tested
        ssh -A root@localhost "/usr/sbin/usermod -P \"$OLDPROFILE\"\"$SEPARATOR\"\"Software Installation\" \"$TARGETUSERNAME\""
        ;;
     "su")   #untested !
        su - root -c "/usr/sbin/usermod -P \"$OLDPROFILE\"\"$SEPARATOR\"\"Software Installation\" \"$TARGETUSERNAME\""
        ;;
     "")  #OI2010/OI2011 or recent Solaris Express 11 *IF* this script is run with apropriate userrights (root,...)
        /usr/sbin/usermod -P "$OLDPROFILE""$SEPARATOR""Software Installation" "$TARGETUSERNAME"
        ;;
    esac
    unset OLDPROFILE SEPARATOR
    echo "Note: other profiles might have been *overwritten* please re-adjust them"
    echo "yourself if necessary!"
    echo ""
    echo "NEW: Profiles Settings:"
    echo "======================="
    /usr/bin/profiles "$TARGETUSERNAME"
    echo "======================="
    echo ""
    echo " you MUST login the target user >$TARGETUSERNAME< again to take the (RBAC) profile's"
    echo " settings into effect\c "
    #well, only if the targetuser itself runs this script, then it makes big sense to stop the script *now*
    if [ "$TARGETUSERNAME" == "$USER" ] 
       then
      echo " and re-run the this script!"
      echo " Exiting this script *now*, logout and login again to re-run this script."
      exit 0
    fi
    echo ""
fi


echo ""
echo "Preparing DNS config for this machine..."
echo " Testing DNS resolution: getent hosts www.opensolaris.org"
getent hosts www.opensolaris.org &> /dev/null
if [ $? -eq 0 ]
   then
   echo ""
   echo "Nameservice seems to be set up already"
   echo ""
 else
   echo ""
   echo "putting a nameserver (might need to be changed) into /etc/resolv.conf"
   echo "checking for    hosts: dns   in /etc/nsswitch.conf and if necessary cp /etc/nsswitch.dns to /etc/nsswitch.conf"
   #ssh -A root@localhost "echo nameserver 4.2.2.2 > /etc/resolv.conf; grep \"hosts:.*dns\" /etc/nsswitch.conf || cp -p /etc/nsswitch.dns /etc/nsswitch.conf"
   ${SUPERCMD} "echo nameserver 4.2.2.2 > /etc/resolv.conf; grep \"hosts:.*dns\" /etc/nsswitch.conf || cp -p /etc/nsswitch.dns /etc/nsswitch.conf "
   #echo 'nameserver 4.2.2.2' > /etc/resolv.conf
   #grep "hosts:.*dns" /etc/nsswitch.conf || cp -p /etc/nsswitch.dns /etc/nsswitch.conf
   echo ""
fi
  

# At this time, SX2010.11 needs to get Sun Studio 12U1 from the opensolaris.org repository.
# So, we'll do that first to save a failure later.
if [ "${OSDIST}" == "SX2010.11" ]; then
	pkg publisher | grep 'opensolaris.org .*(non-sticky' > /dev/null
	if [ $? -eq 1 ]; then
		echo "Setting additional opensolaris.org publisher to pull in missing packages."
		#${SUPERCMD} pkg set-publisher --sticky -g http://pkg.opensolaris.org/release/ opensolaris.org
		${SUPERCMD} pkg set-publisher --sticky -g http://pkg.openindiana.org/legacy/ opensolaris.org
		echo ""
	fi
fi

# This is so HTTPS doesn't give untrusted warnings so often. :)
# The CA list is extracted automatically from Firefox. See http://curl.haxx.se/docs/caextract.html
echo -n "Updating system's trusted Certificate Authorities ... "
if [ "$(/usr/bin/ls -l /etc/openssl/certs | head -1)" == "total 0" ]; then
  if [ ! -x /usr/bin/wget ]; then
    echo ''
    echo '"wget" not found. Please install SUNWwget and try again.'
    exit 1
  fi
  ${SUPERCMD} /usr/bin/wget --quiet -O /etc/openssl/certs/cacert.pem http://curl.haxx.se/ca/cacert.pem
  echo 'done!'
else
  echo 'not needed!'
fi

echo ""
CTEST=$USERTEMP/compiletest-$$.c
echo "Preparing check for compiler test $CTEST ..."

cat > $CTEST << EOF
int
main ()
{

;
return 0;
}
EOF


if [ "${OSDIST}" == "SXCE" ]
 then
 #note: we have actually no special install step for required Solaris SVR4 packages, it is assumed user did a "full install"
 if $CCOMPILERPATH -o $CTEST.binary $CTEST
   then
    echo "running test for ${OSDIST}"
    echo ""
    echo "      $CCOMPILERPATH x   *succeeded*"
    echo ""
   else
    echo ""
    echo "      $CCOMPILERPATH x   *failed* --- repair or replace your compiler, see intructions below"
    echo ""
    echo ""
    echo "go to this URL:"
    echo ""
    echo "      http://developers.sun.com/sunstudio/downloads/express/index.jsp"
    echo "      ---------------------------------------------------------------"
    echo "then click -> Download Now   for Oracle Solaris Studio Express 6/10 Software"
    echo "              ------------"
    echo "You are asked to enter your -> email-address, then click -> Download now"
    echo "                               -------------                ------------"
#we use pkg for regular sunstudio, we use tarfile for studoexpress (can't pe patched anyways)
##    echo "then click on Option 1: Download Package Installer"
    echo "then click on Option 2: Download Tarfile"
    echo "                        ----------------"
    echo "you'll be presented with the \"Select Platform and Language\" question, choose:"
    echo "                             ----------------------------"
    echo "   Platform:  -> x86 or sparc"
    echo "                 ------------"
    echo "   Language:  -> english"
    echo "                 -------"
    echo "   read and -> check the License Agreement, enter your account user/password"
    echo "               -----                                   ----------------------"
    echo ""
    echo "   then click -> Log in and Continue"
    echo "                 -------------------"
    echo "you'll see the final download page. Scroll down to section \"Required Files\" "
    echo "                                                           ---------------"
    echo "Important: copy&paste the download link into this bootstrap script"
    echo "by watching for the Link \"SolarisStudioExpress2010-06-sol-x86.tar.bz2\" and"
    echo "                          -------------------------------------------"
    echo "right-click on that link -> copy link location"
    echo "------------------------    ------------------"
    echo ""
    echo "select your terminal window and then paste the link into the prompt below and press \"ENTER\" two times."
    echo "--------------------                 --------------          ------                 -----------------"
    echo "This script will fetch the file with \"wget\"."
    echo ""
    echo "Important note: go read and accept the License SunStudio prints out later or deinstall and don't use SunStudio."
    echo "we'll go run the installer non-interactively. You may press Ctrl-C now to cancel the installation."
    echo ""
    echo ""
    echo "now paste the download URL here and then press ENTER two times:    (I said two times.)"
    echo ""
    # SUNSTUDIOURL=""
    while true; do read -r -n 50; [ ${REPLY}"" == "" ] && break; SUNSTUDIOURL="${SUNSTUDIOURL}${REPLY}"; done
    cd /var/tmp
    SUNSTUDIOFILENAME=`echo $SUNSTUDIOURL | sed -e 's,.*FileName=/*,,'`
    echo ""
    echo "extracted Filename: $SUNSTUDIOFILENAME"
    echo "download URL:       $SUNSTUDIOURL"
    echo ""
    [ -r $SUNSTUDIOFILENAME"" ] || wget -N -c -O $SUNSTUDIOFILENAME "$SUNSTUDIOURL" || exit 1
                                #wget -N -c -O $SUNSTUDIOFILENAME "$SUNSTUDIOURL" || exit 1

#remember: his script was for setting / changing setup of the test.opensolaris.org buildfarm

    #[ -d /opt/SUNWspro ] && mv /opt/SUNWspro_broken
    if [ -d /opt/SUNWspro ]  && df -k /opt/SUNWspro | grep -- "^-"
       then
        if grep "^/opt/SUNWspro.*-.*/opt/SUNWspro_own.*lofs" /etc/vfstab
           then
            echo "WARNING: lofs mount for /opt/SUNWspro already defined in /etc/vfstab"
           else
             echo "tricking the inherited SUNWspro directory to be an overlay mount."
             echo "please supply the root passwort if you do not use SSH-Agent-forwarding."
             echo "the command to be run is: ssh -A root@localhost \"mkdir /opt/SUNWspro_own && mount -F lofs -O /opt/SUNWspro_own /opt/SUNWspro\" && echo /opt/SUNWspro	-	/opt/SUNWspro_own	lofs	-	yes	- >> /etc/vfstab"
             ssh -A root@localhost "mkdir /opt/SUNWspro_own ; mount -F lofs -O /opt/SUNWspro_own /opt/SUNWspro && echo /opt/SUNWspro -       /opt/SUNWspro_own   lofs    -       yes     - >> /etc/vfstab"
        fi #already in vfstab
    fi #need lofs mount in vfstab

    # if old contentes are in place, stop here and let user remove this
    if [ -r "/opt/SUNWspro/bin/cc" -o -r "/opt/netbeans-[6-]*/bin/netbeans" ]
       then
       echo ""
       echo " $USERTEMP/SUNWspro and/or $USERTEMP/netbeans-[6-]* directory not empty."
       echo " moving new SUNWspro and netbeans into /opt/ failed."
       echo " please cleanup yourself these directories and re-run this script."
       echo " exiting this script *now*."
       exit 1
       fi

    if (echo $SUNSTUDIOFILENAME | grep "tar.bz2$" > /dev/null)
     then # tarfile installer, just decompress into the target directory
      cd /var/tmp
      echo "unpacking compiler (will at least take several minutes)"
      bzip2 -d < $SUNSTUDIOFILENAME | tar xf -
 # new StudioExpress (past 08/11) use new directory, rename that
 # cbe install looks for several directories, anyway just use always SUNWspro 
 # even for express versions (by simply renaming the directory to SUNWspro)
     if [ -d /opt/SUNWspro/bin/cc ] 
        then 
         echo "/opt/SUNWspro/bin/cc already exists. stopping script instead of overwriting."
         exit 1;
     fi
     [ -d /var/tmp/SSX* ] && mv /var/tmp/SSX* /var/tmp/SUNWspro 
     [ -d /var/tmp/solstudioex[0-9]* ] && mv /var/tmp/solstudioex[0-9]* /var/tmp/SUNWspro 
     echo "next is moving compiler to target directory, needs elevated permissions"
     echo " ---- you might be asked for the root password ---- "
     echo "Please provide the root password so we can continue installation."
     ssh -A  root@localhost "[ -d /opt/SUNWspro ] || mkdir /opt/SUNWspro; mv \"$USERTEMP/SUNWspro/*\" /opt/SUNWspro && mv \"$USERTEMP/netbeans-[6-]*\" /opt/"


     else # package installer - it is a self-extracting shell script
      chmod a+rx $SUNSTUDIOFILENAME
       ${SUPERCMD} /var/tmp/$SUNSTUDIOFILENAME --print-sla  2>&1 | cat
       ${SUPERCMD} /var/tmp/$SUNSTUDIOFILENAME --accept-sla 2>&1 | cat 
    fi # 



 fi # we are done $CCOMPILERPATH $CTEST
fi # we are done with SXCE

if echo ${OSDIST} | egrep "OS20[01][0-9].[0-9n][0-9n]|SX20[01][0-9].[0-9n][0-9n]|OI201[012].[0-9][0-9][0-9]|SOL11\.|SOL12\.|OMNIOS" > /dev/null
 then
 # install missing packages or if selected repository has updated versions of a package, do update of existing and add missing packages
 # this is done after checking and evenutally installing the SunStudioExpress compiler.
 # Now, before installing any other packages, check for a already working SunStudio compiler (currently, look for SunStudioExpress)
 # if necessary, install the compiler from a suitable repository


CCOMPILEROK=0

echo "Running tests for ${OSDIST}"
for CCOMPILER in $CCOMPILERPATHLIST; do

  if [ $CCOMPILEROK -ne 1 ]; then

    COMPILERSTATUS=0

    echo "Testing this compiler now: $CCOMPILER"
    echo "Verify if (Sun) C compiler is present and executable:"

    if [ -x "$CCOMPILER/bin/cc" ]; then
      echo "   + Compiler binary is executable." 
      COMPILERSTATUS=1

    else
      echo "   - No, compiler binary is not executable or is not present."


    fi # verify executable compiler binary

    if [ $COMPILERSTATUS -eq 1 ]; then
      # test compiler we think to have found or installed right now
      if $CCOMPILER/bin/cc -o $CTEST.binary $CTEST; then
        COMPILERSTATUS=2
      fi
    fi

    if [ $COMPILERSTATUS -eq 2 ]; then
      echo ""
      echo "      $CCOMPILER x   *succeeded*"
      echo ""
      CCOMPILEROK=1
      export CCOMPILERPATH=$CCOMPILER/bin/cc
    else
      echo ""
      echo "      $CCOMPILER x   *failed*"
      echo ""
    fi

  fi # Our compiler is a good one! ;)

done
   

if [ $CCOMPILEROK -ne 1 ]; then
    echo "Specified compiler executable(s) not found, installing package"
    echo "$COMPILERPACKAGEIPS from your defined repository."
#    echo "${SUPERRIGHTS} pkg install $PKG_ACCEPT_SHOW_LICENSE $COMPILERPACKAGEIPS"
#    ${SUPERCMD} /usr/bin/pkg install $PKG_ACCEPT_SHOW_LICENSE $COMPILERPACKAGEIPS
ls /dummynotthere
    ret=$?
    if [ $ret == 0 -o $ret == 4 ]
      then
        echo "."
      else
        #try again, but do a pkg refresh first: (new package names e.g. pkg://developer/sunstudioexpress)
#        echo "${SUPERRIGHTS} pkg refresh"
#        ${SUPERCMD} /usr/bin/pkg refresh
        #echo "${SUPERCMD} /usr/bin/pkg install $PKG_ACCEPT_SHOW_LICENSE consolidation/desktop/gnome-incorporation"
        #${SUPERCMD} /usr/bin/pkg install $PKG_ACCEPT_SHOW_LICENSE consolidation/desktop/gnome-incorporation
#        echo "${SUPERRIGHTS} pkg install $PKG_ACCEPT_SHOW_LICENSE $COMPILERPACKAGEIPS"
#        ${SUPERCMD} /usr/bin/pkg install $PKG_ACCEPT_SHOW_LICENSE $COMPILERPACKAGEIPS

ls /dummynotthere
	ret=$?
	if [ $ret -ne 0 -o $ret -ne 4 ]; then  #try to install the tarball
        #we only check in the local directory for a file patten match  $SOLSTUDIOTARBALLPATTERN
		echo "trying to find a compiler tarball for installation in directory:"
                #might be preset from outside! do not set to empty  CCOMPILERTARBALLFILE=""
                for solstudiodir in ${CCOMPILERTARBALLDIR}
                   do
                   [ -n ""${CCOMPILERTARBALLFILE} ] && break
                    echo "Directory: $solstudiodir"
                   for tarballpattern in `ls -1d * | gegrep ${CCOMPILERTARBALLPATTERN}`
                       do
                         [ -n ""${CCOMPILERTARBALLFILE} ] && break
                         echo "Searchpattern: $tarballpattern"
                         CCOMPILERTARBALLFILE=$( ls -1d $solstudiodir/* | egrep "$tarballpattern" | tail -1 )
                       done #tarballpattern
                   done #solstudiodir

                 # install the compiler found right now and pass on ret=0 for the next section indicating success
                 if [ -n ""${CCOMPILERTARBALLFILE} ] ; then 
                    #hardcoded target path, hoping the user has created it's personal zfs filesystem before
                    # note sizes are up to a gigabyte, so don't mess around with the disk space :)
# bzip2 -d < ${CCOMPILERTARBALLFILE} | tar tvf - | grep "/s.*studio12" | head -1 | sed -e s'/.* //'
#SolarisStudio12.3-solaris-x86-bin/solarisstudio12.3
# bzip2 -d < ${CCOMPILERTARBALLFILE} | tar tvf - | grep "/s.*studio12" | head -1 | sed -e s'/.* //' -e 's?.*/??'
#solarisstudio12.3


                    EXTRACTEDTARGETTEMP=$( bzip2 -d < ${CCOMPILERTARBALLFILE} | tar tvf - | grep "/s.*studio12" | head -1 | sed -e s'/.* //' )     # SolarisStudio12.3-solaris-x86-bin/solarisstudio12.3
                    EXTRACTEDTARGETDIR=$( basename $EXTRACTEDTARGETTEMP )    # solarisstudio12.3
                    EXTRACTEDTARBASEDIR=$( dirname $EXTRACTEDTARGETTEMP )    # SolarisStudio12.3-solaris-x86-bin
                    echo "mkdir & changing to target directory /opt/${EXTRACTEDTARGETDIR} and extract the compiler tarball..."
                    if [ ! -d /opt/${EXTRACTEDTARGETDIR} ] ; then
                      echo "mkdir /opt/${EXTRACTEDTARGETDIR}"
                      $SUPERCMD mkdir /opt/${EXTRACTEDTARGETDIR} || exit 1  #something went wrong
                    fi # mkdir 
                    echo "cd /opt/${EXTRACTEDTARGETDIR}"
                    cd /opt/${EXTRACTEDTARGETDIR} || exit 1  #something went wrong
                    echo "extract tarball here, then relocate directories into place,"
                    echo "unpacking the compiler will at least take several minutes"
                    TEMPSCRIPT=`mktemp`
                    echo "bzip2 -d < ${CCOMPILERTARBALLFILE} | tar xf -"  > $TEMPSCRIPT
                    chmod a+x $TEMPSCRIPT
                    $SUPERCMD $TEMPSCRIPT
                    rm $TEMPSCRIPT
                    #relocate stuff down to targetdirectory
                    echo "mv /opt/${EXTRACTEDTARGETDIR}/${EXTRACTEDTARBASEDIR}/${EXTRACTEDTARGETDIR}/* `pwd`"
                    $SUPERCMD mv /opt/${EXTRACTEDTARGETDIR}/${EXTRACTEDTARBASEDIR}/${EXTRACTEDTARGETDIR}/* `pwd`
                    ret=$?
##TODO## eval the ret value, if okay, export  CCOMPILERPAT
                    export CCOMPILERPATH=/opt/${EXTRACTEDTARGETDIR}/bin/cc
                    #hardcore that we are done for now
                    ret=0 

                 fi #CCOMPILERTARBALLFILE non empty (which is we had something usable to install)
         
        fi #try to install the tarball

        

	if [ $ret -ne 0 -o $ret -ne 4 ]; then  #all failed, go instruct the user to install compiler manually
		echo "The compiler failed to install! Please try to manually install the package"
		echo "$COMPILERPACKAGEIPS and try running this script again."
		echo "Display your current IPS publisher with the command:"
                echo "     pkg publisher"
                if echo ${OSDIST} | egrep "SX20[01][0-9].[0-9n][0-9n]|OI201[012].[0-9][0-9][0-9]|OMNIOS" > /dev/null
                        then
			echo ""
			echo "========================================================================"
			echo "========================================================================"
			echo "You may need to do the following and run this script again:"
			echo ""
                        echo "HISTORIC: there was a repository/publisher for opensolaris providing the compiler as well"
			#echo "${SUPERRIGHTS} pkg set-publisher --non-sticky -O http://pkg.opensolaris.org/release/ opensolaris.org"
			#now outdated compiler 12.1# echo "${SUPERRIGHTS} pkg set-publisher --non-sticky -O http://pkg.openindiana.org/legacy/ opensolaris.org"
                        echo ""
                        echo "TODAY: this repository/publisher is *gone*, now you have to install the compiler *yourself*."
                        echo "Download solstudio 12.2 or 12.3 now and check if you can accept the licensing."
                        #echo "you may use the tarball. (cd /opt; extract tarball; mv ./SolarisStudio12.3-solaris-x86-bin-ML/solstudio12.3 .; rmdir ./SolarisStudio12.3-solaris-x86-bin-ML)"
                        echo "Download the \"tar\" or \"bin\" pure tarballs and tell the bootstrap script"
                        echo "where is is located: e.g. export CCOMPILERTARBALLFILE=/here/is/SolarisStudio12.3-solaris-x86-bin.tar.bz2"
                        echo "Or you download the installer and use the gui and accept all defaults."
                        echo "The preferred install target directory is: /opt/solarisstudio12.3  (or /opt/solstudio12.2)"
                        echo ""
                        echo "Then * * * re-run this script * * *. It will use the environment variable from above *or*"
                        echo "search those directories for the compiler extracted right above:"
                        echo "(we call e.g. /opt/solarisstudio12.3/bin/cc during the next run)"
                        echo "$CCOMPILERPATHLIST" 
			echo ""
		fi #SX2010.11/OI2010/OI2011 special case
		exit $ret
	fi #$ret !=0 or !=4 (this it the check after late install case)
    fi #$ret !=0 or !=4 (this is the case "first attempt failed" case)
##TODO## only true if the old 12.1 could be installed from the opensolaris ips repository:
    export CCOMPILERPATH=/opt/sunstudio12.1/bin/cc
fi

echo "C Compiler is set to $CCOMPILERPATH"

   
 # now install all the other missing pieces from the repository, use IPS package names defined in the top of this script

  echo ""
  echo "Install missing packages needed for most compiles. Next command may need"
  echo "some time to complete for download and install..."
  echo ""
  echo "Install system headers first:"
  echo "(Allowed to fail because it's for instance integrated in other packages or renamed)"
  [ -r /tmp/nopkg ] || for PACKAGE in $PACKAGESADDIPSALLOWEDFAIL ; do
                       echo "${SUPERRIGHTS} pkg install $PKG_ACCEPT_SHOW_LICENSE $PACKAGE"
                       ${SUPERCMD} /usr/bin/pkg install $PKG_ACCEPT_SHOW_LICENSE $PACKAGE
                       done #for PACKAGE
  echo "Install second (NOT allowed to fail): $PACKAGESADDIPS"
  [ -r /tmp/nopkg ] || ${SUPERCMD} /usr/bin/pkg install $PKG_ACCEPT_SHOW_LICENSE $PACKAGESADDIPS
  ret=$?
  if [ $ret == 0 -o $ret == 4 ]
    then
    # 0 installed, 4 already installed nothing to do
    echo "pkg install of required packages successful (return code $ret)"
   else
    echo "Error, pkg install $PKG_ACCEPT_SHOW_LICENSE $PACKAGESADDIPS returned an error (return-code: $ret). Abort."
    echo "Please fix the error(s) and re-run this script with the same arguments"
    exit 1
   fi

   ##TODO## running this script as non-root fails - new ideas wanted
  if [ -r /usr/share/sgml/docbook/docbook-catalog-install.sh ] 
    then
     echo "Running /usr/share/sgml/docbook/docbook-catalog-install.sh ..."
     echo "This may take a while ..."
     ${SUPERCMD} chmod a+rx /usr/share/sgml/docbook/docbook-catalog-install.sh
     ${SUPERCMD} /usr/share/sgml/docbook/docbook-catalog-install.sh
     echo "finished docbook-catalog-install.sh (exit was code: $?)"
     fi  

#OmniOS stops delivering gcc-3, so install a replacement (only needed to build SFEgcc.spec,
#needs removal of those symlinks later on)
if [ ${RUNOM201X_GCC3_SYMLINKS} == "yes" ]
  then
  ${SUPERRIGHTS} mkdir -p /usr/sfw/bin 2>&1 && echo "created dummy /usr/sfw/bin directory"
  for filepath in bin/c++ bin/g++ bin/gcc bin/gcov
    do
    [ -f /usr/sfw/$filepath ] ||  ${SUPERRIGHTS} ln -s /opt/gcc-4.8.1/$filepath /usr/sfw/bin/
  done #for filepath ln -s
fi #RUNOM201X_GCC3_SYMLINKS
  

fi # end we are done with OS20[01][0-9].[0-9][0-9]



#if we are on the testfarm then there might be a lot of files unpackaged but on the system
#let us do a little housekeeping

if echo ${OSDIST} | egrep "OS20[01][0-9].[0-9n][0-9n]|SX20[01][0-9].[0-9n][0-9n]|OI201[012].[0-9][0-9][0-9]|SOL11\.|SOL12\.|OMNIOS" > /dev/null
  then
  # remove packages if any, might fail but then ignore and try to go on
  # no packaged file here, if they where, we would do an pkg uninstall <packagename>
  # remove files possibly not in control of the package system
  echo "Removing some files not referenced in the packaging system which get in the way"
  echo "(pkg would complain about the files already existing) ..."

  removepattern="/opt/dtbld/bin/pkgbuild /opt/dtbld/bin/pkgtool /opt/dtbld/bin/spectool /opt/dtbld/lib/pkgbuild-[0-9].[0-9]*[0-9]* ${USERHOMEDIR}/.pkgbuildmacros"
  echo "Sorry, but I'm removing file(s)/directories: $removepattern"
  [ -r "${USERHOMEDIR}"/.pkgbuildmacros ] && mv ${USERHOMEDIR}/.pkgbuildmacros ${USERHOMEDIR}/.pkgbuildmacros.saved.$$
  ${SUPERCMD} /usr/bin/rm -r $removepattern 2>&1 | grep -v "such file"

  # check if remaining directories have suitable owner/permissions
  # might only happen with desktop-cbe 1.7.x generations
  [ -d /opt/dtbld/bin ] && ${SUPERCMD} chown root:bin /opt/dtbld/bin /opt/dtbld  && ${SUPERCMD} chmod 755 /opt/dtbld/bin /opt/dtbld
  [ -d /opt/dtbld/lib ] && ${SUPERCMD} chown root:bin /opt/dtbld/lib /opt/dtbld  && ${SUPERCMD} chmod 755 /opt/dtbld/lib /opt/dtbld

fi # removing old packages or vagabunding files before cbe-install on "OS20[01][0-9].[0-9][0-9]"


#if we are on the testfarm then there might be a shell environment set with PATHs and so on
#let us do a little housekeeping:
# clean the .bash_profile from the PATH to preinstalled tools which are ususally set on the test farm and warn the user
if echo ${OSDIST} | egrep "OS20[01][0-9].[0-9n][0-9n]|SX20[01][0-9].[0-9n][0-9n]|OI201[012].[0-9][0-9][0-9]|SOL11\.|SOL12\.|OMNIOS" > /dev/null
  then
  echo "Checking for environment settings in the file \".bash_profile\" we want to clean."
  echo "Note: You need to re-login to take the new PATH to effect outside of this"
  echo "installation script."
  echo "Note: This step addresses test farm zones"
  CLEANPATTERNPATH="(/opt/onbld/bin:?|/usr/X11/bin:?|/opt/dtbld/bin:?|/opt/jdsbld/bin:?|/usr/ccs/bin:?|/usr/gnu/bin:?|/usr/sbin:?|/bin:?|/usr/sfw/bin|:?/opt/SunStudioExpress/bin:?)"

  if egrep "^export PATH.*""$CLEANPATTERNPATH" ${USERHOMEDIR}/.bash_profile > /dev/null 2>&1
    then
     #found unwanted content in PATH
     echo "I'm sorry, I'll reset your PATH in .bash_profile to a new one"
     RELOGON=yes
     echo "commenting out the \"PATH\" setting"
     perl -pi.bak -e 's/^(export PATH=)/#\1/' .bash_profile
     echo "adding PATH=/usr/bin:/bin  to the end of your .bash_profile"
     echo "export PATH=/usr/bin:/bin" >> .bash_profile
     echo "changed your .bash_profile. Please check contents and *relogon* later to have changes be effective."
  #only valid for this login-session:  (seen wrong binaries used elseways)
     export PATH=/usr/bin:/bin
  fi #egrep PATH CLEANPATTERNPATH

fi # on OS20nn.nn


echo "Downloading CBE"

cd "$USERTEMP"
ret=$?
if [ $ret -ne 0 ]; then
  echo "Could not get CBE into $USERTEMP. Please try to clean up manually."
  exit $ret
fi


#if we run on a more recent OS distro, then use a newer CBE
######yes on SX2010.nn OI2010/OI2011.nnn -- but NOT on OS2009.11 and NOT on OS2010.02/OS2010.03 aka build 133/134 for instance
#######subject for discussion if OS2009.11 should as well receive desktop-cbe-1.7 or such versions
#if [ $(echo ${OSDIST} | egrep "SX201[0-9].[0-9n][0-9n]|OI201[012].[0-9][0-9][0-9]") ]; then
if [ $(echo ${OSDIST} | egrep "OS20[01][0-9].[0-9n][0-9n]|SX20[01][0-9].[0-9n][0-9n]|OI201[012].[0-9][0-9][0-9]|SOL11\.|SOL12\.|OMNIOS") ] > /dev/null
 then
 CBEURL=${CBEURL2}
fi

CBEFILE=`echo $CBEURL | sed -e 's|.*%2F\(.*\)$|\1|'`
pwd
mkdir download
cd download
wget -O $CBEFILE -N -c "$CBEURL" || exit 1
cd "$USERTEMP" || exit 1

#decompress jds-cbe *or* desktop-cbe. This simple code only handles one of them at the same time in /var/tmp correctly. So just have not both at a time in this directory.
#extract base filename of the download URL to get the filename
#CBEFILE=`basename $CBEURL`
rm -rf desktop-cbe*
bzip2 -d < download/$CBEFILE | /usr/bin/tar xfe -
if [ $? -ne 0 ]
  then
    echo "CBE could not be properly extracted. Please clean up the results of extracting"
    echo "$CBEFILE in $USERTEMP manually, then try executing this"
    echo "script again."
    exit 1
fi

#added: patch the cbe-install/desktop-install to remove a failing test " -a -d /var/pkg/catalog" on newer IPS based systems (the perl -pi line)

cd "$USERTEMP"

if echo $CBEFILE | egrep -- "jds-cbe-"
  then
    cd jds-cbe-[0-9]*[0-9] || exit 1

    #bug already removed in cvs of later then jds-cbe-1.6.2
    perl -pi.bak -e 's?-x /usr/bin/pkg -a -d /var/pkg/catalog?-x /usr/bin/pkg?; s/ *SUNWsfwhea */ /;' ./*-install

    #make PATH sane (especially avoid /usr/gnu/bin and pickup wrong cc binary/link)
    $EXCMD ./*-install << EOF
2
i
export PATH=/usr/bin:/bin
.
wq
EOF

    #prepare the "input"file to the installscript to answer questions
    grep -v "^#" <<EOF > "$USERTEMP"/installcbe-script-$$.inputfile
#comments are filtered out at runtime
#accept note to pkgbuildmacros by just enter "Press Enter to continue"

#path to the C compiler
$CCOMPILERPATH
#says this CC is not the recommended version, type yes to accept anyway
yes
#install additional packages? type yes to do so
yes
#replace/uninstall all packages?
yes
EOF

    ls -1 "$USERTEMP"/installcbe-script-$$.sh  2>/dev/null && exit 1
    cat > "$USERTEMP"/installcbe-script-$$.sh <<EOF || exit 1
#!/usr/bin/bash
cd "$USERTEMP"/jds-cbe-[0-9]*[0-9] || exit 1
${SUPERCMD} ./*-install < "$USERTEMP"/installcbe-script-$$.inputfile
EOF
    chmod a+rx "$USERTEMP"/installcbe-script-$$.sh
    echo "*****************"
    [ -z "$USESU" ] || echo "If you are prompted for a password, please enter the password of the compile user specified on the commandline"
    $USESU "$USERTEMP"/installcbe-script-$$.sh

#20091122 remove broken CBEsvn and use the system provided svn, do this if [ -x /usr/bin/svn ] is true
#the CBEsvn from jds-cbe 1.6.2 links to a non present libdb.so* which is bad
if [ -x /usr/bin/svn ] 
  then
    # there should be a SUNWsvn or equivalent, because otherwise we wouldn't have a /usr/bin/svn
    yes | ${SUPERCMD} /usr/sbin/pkgrm CBEsvn
 fi # -x svn

fi # jds-cbe



# we prepare the input for to the desktop-cbe-installer for the current OS DISTs 
# to simplify the if-then-else-fi logic for the install itself
# prepare for SXCE, see below for OS20[01][0-9]
if [ "${OSDIST}" == "SXCE" ]
  then
    rm "$USERTEMP"/desktop-cbe-inputfile.[0-9]*
    cat > "$USERTEMP"/desktop-cbe-inputfile.$$  <<EOF 
#comments are filtered out at runtime
#If you wish to use a different build directory, you can define it
#in ${USERHOMEDIR}/.pkgbuildmacros as follows:
#
#%_topdir /path/to/my/build/area
#
#Would you like to do this now? [no]:
no
#Would you like to configure more compilers for use with the Desktop CBE? [no]:
no
#2 - Sun Studio 12 5.9 (Mars) in /opt/SUNWspro/bin
#Please select the default compiler [2]: 
2
#Would you like install the tools for GNOME? [yes]:
no
#Would you like install the tools for KDE? [yes]:
no
#Would you like install the tools for SFE? [yes]:
yes
#The following tools are optional: rsync cvs
#Would you like install the optional tools? [yes]:
no

EOF
fi
# we like it simple, overwrite the inputfile in case the file already exists...
if echo ${OSDIST} | egrep "OS20[01][0-9].[0-9n][0-9n]|SX20[01][0-9].[0-9n][0-9n]|OI201[012].[0-9][0-9][0-9]|SOL11\.|SOL12\.|OMNIOS" > /dev/null
  then
    # we *are* overwriting the just created input file above!
    rm "$USERTEMP"/desktop-cbe-inputfile.[0-9]*
    cat > "$USERTEMP"/desktop-cbe-inputfile.$$  <<EOF 
#+ ./cbe-install
#Desktop Common Build Environment (CBE) Installer version 1.7.0-rc1
#Using "pkg" packaging system
#
#The following compilers were found on your system:
#1 - GNU gcc 3.4.3 (3) in /usr/bin
#2 - GNU gcc 3.4.3 (3) in /usr/sfw/bin
#3 - Sun Studio Express 5.10 (Ceres) in /opt/SunStudioExpress/bin
#Would you like to configure more compilers for use with the Desktop CBE? [no]:
no
#
#The following compilers were found on your system:
#1 - GNU gcc 3.4.3 (3) in /usr/bin
#2 - GNU gcc 3.4.3 (3) in /usr/sfw/bin
#3 - Sun Studio Express 5.10 (Ceres) in /opt/SunStudioExpress/bin
#Please select the default compiler [3]:
3
#
#The Desktop CBE includes tools for building GNOME, KDE and/or SFE packages
#It also includes some optional tools. Please select the tools you wish
#to install.
#
#Would you like install the tools for GNOME? [yes]: no
no
#Would you like install the tools for KDE? [yes]: no
no
#Would you like install the tools for SFE? [yes]: yes
yes
#
#The following tools are optional: rsync cvs
#Would you like install the optional tools? [yes]: no
no
EOF
fi # cbe-install on (see above for more OSDIST...) "OS20[01][0-9].[0-9][0-9] ... |SOL11\.|SOL12\."

cd "$USERTEMP"

#SUNWcar SUNWkvm on OI(/others?) not found by pkg (renamed package)
#so switch off CBE's install checking with pkgadd -a adminfile.dontask
#we change desktop-cbe's own admin file, see perl below

if echo $CBEFILE | egrep -- "desktop-cbe-[0-9]"
   then
     cd desktop-cbe-[0-9]*[0-9] || exit 1
     #bug already removed in cvs of later then jds-cbe-1.6.2
     perl -pi.bak -e 's?-x /usr/bin/pkg -a -d /var/pkg/catalog?-x /usr/bin/pkg?; s/SUNWsfwhea */ /;' ./*-install
#bootstrap itself checks required packages
     perl -pi.bak2 -e 's?(check_cbe_dependencies_pkg .CBE_PKG_DEPENDENCIES)?echo "dep checks disabled."; DEPS_OK=yes DEPS_INSTALLED=yes #disabled# \1?; s/^ALT_.*=(\"SUNW|SUNW)(gnu-coreutils|gnu-diffutils|gm4|aconf|gnu-automake.*|bison|flexlex|libtool|gmake|svn)/#disabled# \1\2/;' ./*-install
#remove dependency checking (IPS based systems do not resolve SUNWcar SUNWkvm as being present with new name!!
     perl -pi.bak3 -e 's?instance=unique?instance=overwrite?;s?idepend=quit?idepend=nocheck?;s?rdepend=quit?rdepend=nocheck?' ./*-install
#KDE_MODULES="m4 autoconf automake libtool bison coreutils diff flex gettext subversion gnuawk gnused cmake make yasm"
     perl -pi.bak4 -e 's?(yasm)?? if /^KDE_MODULES=/' ./*-install
     perl -pi.bak5 -e 's?/usr/ccs/bin:{0,1}??' ./*-install


     chmod +w ./*-install
     $EXCMD ./*-install << EOF
2
i
export PATH=/usr/bin:/bin
.
wq
EOF
    ls -1 "$USERTEMP"/installcbe-script-$$.sh  2>/dev/null && exit 1
    ls -1 "$USERTEMP"/installcbe-script-$$.sh && exit 1
    cat > "$USERTEMP"/installcbe-script-$$.sh <<EOF || exit 1
#!/usr/bin/bash
cd "$USERTEMP"/desktop-cbe-[0-9]*[0-9] || exit 1
${SUPERCMD} ./*-install < "$USERTEMP"/desktop-cbe-inputfile.$$
EOF
    chmod a+x "$USERTEMP"/installcbe-script-$$.sh
    echo "*****************"
    [ -z "$USESU" ] || echo "If you are prompted for a password, please enter the password of the compile user specified on the commandline"
 #this installscript nees ether "Primary Administrator" or "Software Installation" profile
 #it can't honour the roles="root"
 #assuming the running user has profile "Software Installation" already assigned
 # -->> no need to use SUPERCMD
 ##TODO## if this works for all OSDIST types, then the inputfile from above can be retired
 #./cbe-install -n --sfe --gnome --compiler $CCOMPILERPATH
 ./cbe-install -n --compiler $CCOMPILERPATH
fi #endfi desktop-cbe-*


#CBE 1.8.x is reduced to fewer extra packages, so if this is used use other options
# desktop-cbe-mini-1.8.0.tar.bz2

if echo $CBEFILE | egrep -- "desktop-cbe-mini-[0-9]\..*tar.bz2"
   then
     cd desktop-cbe-mini-[0-9]*[0-9] || exit 1
     #bug already removed in cvs of later then jds-cbe-1.6.2
     perl -pi.bak -e 's?-x /usr/bin/pkg -a -d /var/pkg/catalog?-x /usr/bin/pkg?; s/SUNWsfwhea */ /;' ./*-install
#bootstrap itself checks required packages
     perl -pi.bak2 -e 's?(check_cbe_dependencies_pkg .CBE_PKG_DEPENDENCIES)?echo "dep checks disabled."; DEPS_OK=yes DEPS_INSTALLED=yes #disabled# \1?; s/^ALT_.*=(\"SUNW|SUNW)(gnu-coreutils|gnu-diffutils|gm4|aconf|gnu-automake.*|bison|flexlex|libtool|gmake|svn)/#disabled# \1\2/;' ./*-install
#remove dependency checking (IPS based systems do not resolve SUNWcar SUNWkvm as being present with new name!!
     perl -pi.bak3 -e 's?instance=unique?instance=overwrite?;s?idepend=quit?idepend=nocheck?;s?rdepend=quit?rdepend=nocheck?' ./*-install
#KDE_MODULES="m4 autoconf automake libtool bison coreutils diff flex gettext subversion gnuawk gnused cmake make yasm"
     perl -pi.bak4 -e 's?(yasm)?? if /^KDE_MODULES=/' ./*-install
  # not working, workaround below
     perl -pi.bak5_remove_ccs -e 's?/usr/ccs/bin:{0,1}??' ./*-install
     perl -pi.bak5_remove_ccs_workaround -e 's?/usr/ccs/bin:{0,1}?? if /PATH.*\/usr\/ccs\/bin:/' `grep -l "ccs/bin" ext-sources*/env*`

  # not working
  #   perl -pi.bak6 -e 's?(\"x\$prof_pri_adm\" = x)?$1 -o \"x\$prof_sw_inst\" = x ?' ./*-install
  # cut out the profiles check, we already did before
     perl -pi.bak6b -e 's?\[ .x\$prof_pri_adm. = x -o .x\$my_id. = x0 \]? /bin/false ?' ./*-install

  #we don't want the mini-cbe-install check the PKG server, its done by the
  #user at the end of the bootstrap run. So replace the values with "online" and "false"
  #   server_state=`svcs -H -o STATE svc:/application/pkg/server:default`
  #   read_only=`svcprop -c -p pkg/readonly svc:/application/pkg/server:default`
     perl -pi.bak7.server_state -e 's?server_state=.*?server_state=online?' ./*-install
     perl -pi.bak8.read_only    -e 's?read_only=.*?read_only=false?' ./*-install

  #disable dependency checks, pkgtool/pkgbuild runs anyways
     perl -pi.bak9.nodeps -e 's? build ? --nodeps build ? if /pkgtool.*pkgbuild.spec/' ./*-install
  #mini-cbe misinterprets uname -v = 5.11 as osbuild 110 and thats lower then 133
     perl -pi.bak10.s11is5.11 -e 's?myos_bld=.uname -v .*? myos_bld=999 ? if /^ *myos_bld=/' ./*-install

  #mini-cbe misinterprets uname -r = 5.12 or 5.11 without changing tarbal version number
     perl -pi.bak11.anyos_is_5.12 -e 's?myos_rel=.uname -r.*? myos_rel=5.12 ? if /^ *myos_rel=/' ./*-install

  #use pkgtool instead of pkgbuild for CBE itself
  #and add --src $rootdir$pkgbuild_topdir/SOURCES
    perl -pi.bak12.usepkgbuild_w_src -e 's?logrun_quiet.*/usr/bin/pkgbuild ?logrun_quiet /usr/bin/pkgtool --src \$rootdir\$pkgbuild_topdir/SOURCES ?; s? -ba ? build ?;' mini-cbe-install 
  #use the shortnames, so with IPS or without we get what we want:
    perl -pi.bak13.shortnames -e 's?pkg_try_install cbe/desktop/.*? ? if /pkg_try_install cbe\/desktop/' mini-cbe-install 

  #try remoting the return 1
  #  pkg_try_install $CBE_PACKAGES $CBE_DEPENDENCIES # || return 1
    perl -pi.bak14.noreturn -e 's? || return 1?? if /"pkg_try_install .CBE_PACKAGES .CBE_DEPENDENCIES.*return 1"/' mini-cbe-install 

  #move ext-sources out of the way. it is found at pkgtool run and env.sh etc. are copied again, after @CBE_* values are updates -> so lost
 #"\$mydir/ext-sources/"
    [ -d ext-sources ] && mv ext-sources ext-sources-mini-cbe
    perl -pi.bak15.ext-sources-ootw  -e 's?\$mydir/ext-sources/?\$mydir/ext-sources-mini-cbe/?' mini-cbe-install

    #change target directory for copies of the env.sh, gendiff and so on. do not put
    #this into $HOME/packages/SOURCES, it gets overwritten after the sed application...
    # $mydir/ext-sources-mini-cbe/env.csh > $rootdir$pkgbuild_topdir/SOURCES/env.csh" || \
   #     return 1
  #  log "Copying ld-wrapper, gendiff"
  #  logrun bash -c "cp $mydir/ext-sources-mini-cbe/ld-wrapper $rootdir$pkgbuild_topdir/SOURCES" || \
  #      return 1
  #  logrun bash -c "cp $mydir/ext-sources-mini-cbe/gendiff $rootdir$pkgbuild_topdir/SOURCES" || \
  #      return 1
  #  logrun bash -c "mkdir -p $rootdir$pkgbuild_topdir/SPECS" || \
  #      return 1
  #  logrun bash -c "cp $mydir/include/CBE.inc $rootdir$pkgbuild_topdir/SPECS/" || \
  #      return 1
  #  logrun bash -c "cp $mydir/include/default-depend.inc $rootdir$pkgbuild_topdir/SPECS/" || \
  #      return 1

    #save time and avoid common packages installation (takes a longer while)
    perl -pi.bak16.tmp.nopkg  -e 's?pkg_try_install?\[ /tmp/nopkg \] || pkg_try_install? if /pkg_try_install .CBE_PACKAGES .CBE_DEPENDENCIES/' mini-cbe-install

    #change the OS version to 5.12 if we run on 5.11 or 5.12
    uname -r | ggrep -w "5.1[12]" 1>/dev/null && perl -pi.bak17.change5.11_5.12 -e 's?x5.11?x5.12?;' mini-cbe-install

    # remove the dependency on perl from the spec file
#logrun_quiet bash -c "$tmp_build_dir/bin/pkgtool --src $tmp_build_dir/packages/SOURCES --nonotify --define \"pkgbuild_prefix /usr\" --define \"_topdir $tmp_build_dir/packages\" --nodeps build --update-if-newer $tmp_build_dir/src/pkgbuild-$PKGBUILD_VERSION/pkgbuild.spec" || return 1
     
    perl -pi.bak18.remove.perl.dependency  -e '/s?x5.11?x5.12?' mini-cbe-install
    patch -b -z .jposug -p0 < $USERHOMEDIR/mini-cbe-install.patch
    patch -b -z .jposug -p0 < $USERHOMEDIR/CBEenv.spec.patch
    cp $USERHOMEDIR/pkgbuild-1.3.103.patch .
#gnu gpatch not recognized as really gnu patch - .bak19.gpatch
    chmod +w mini-cbe-install
    $EXCMD mini-cbe-install << EOF
/bash .*bin.pkgtool.* build .*PKGBUILD_VERSION.pkgbuild.spec
i
gsed -i.bak.remove.perl.dependency -e 's/^.*Requires:.*perl/#perl/' \$tmp_build_dir/src/pkgbuild-\$PKGBUILD_VERSION/pkgbuild.spec

.
wq
EOF

    #preventive measure: uninstall SVR4 pkgbuild before in any case
   
    ${SUPERCMD} pkg uninstall pkgbuild
    yes | pfexec /usr/sbin/pkgrm SFpkgbuild   2>/dev/null
    yes | pfexec /usr/sbin/pkgrm SFpkgbuild.2 2>/dev/null
    yes | pfexec /usr/sbin/pkgrm SFpkgbuild.3 2>/dev/null
    pfexec pkg uninstall cbe/desktop/CBEenv 2>/dev/null 
    yes | pfexec /usr/sbin/pkgrm CBEenv   2>/dev/null
    yes | pfexec /usr/sbin/pkgrm CBEenv.2 2>/dev/null
    yes | pfexec /usr/sbin/pkgrm CBEenv.3 2>/dev/null

    pwd
    echo ./mini-cbe-install -n --compiler $CCOMPILERPATH
    ./mini-cbe-install -n --compiler $CCOMPILERPATH


    #sanity check: is
    if ! test -f /opt/dtbld/bin/env.sh; then
         echo "error. CBEenv script /opt/dtbld/bin/env.sh is not found, please fix the error"
         exit 1
    fi #env.sh exists

    #sanity checks: is placeholder @CBE_ replaced in env.sh and this tells "CBEenv" is installed?
    if grep "@CBE_" /opt/dtbld/bin/env.sh >/dev/null; then
         echo "error in CBEenv, macros are not replaced or CBEenv is not installed at all"
         grep "@CBE_" /opt/dtbld/bin/env.sh
         echo "please check error with CBEenv compilation / installation and then"
         echo "re-run this bootstrap script"
         exit 1
    fi #grep @CBE sanity check

fi #endfi mini-cbe-*
 
#sanity check if CBE has been successfully installed
if [ -x $TOOLSPREFIX/bin/pkgtool ] 
  then
  echo "checking for executable pkgtool ... yes"
 else
  echo "Check for executable pkgtool has failed. Probably CBE did not install propperly. Please fix the erorrs (probably in this bootstrap script and re-run this script"
  exit 1
fi #executable $TOOLSPREFIX/pkgtool

#we work through "su - $TARGETUSERNAME -c 'runthiscommand'"
#which results in using users permissions and homedirectory


#spec-files-extra checkout
echo "SFE - checking out the spec-files-extra repository"
echo "(skipped if already exists [ -d ${SVNTARGETBASEPATH}/spec-files-extra/.svn ] )"

if [ -d ${SVNTARGETBASEPATH}/spec-files-extra/.svn ]
  then
   echo "spec-files-extra already exists, no svn checkout done."
 else
    echo "*****************"
    echo "switch user to the User-ID who stores the SVN repository."
    echo "Please enter the password for the user \"${TARGETUSERNAME}\" if prompted"
    echo "trying to auto-accept the certificates"
    do_su "$SVNCHECKOUT"
fi


#parked##spec-files-jucr checkout
#parked#echo "JUCR - checking out the spec-files-jucr repository"
#parked#echo "(skipped if already exists [ -d ${SVNTARGETBASEPATH}/spec-files-jucr/.svn ] )"
#parked#
#parked#if [ -d ${SVNTARGETBASEPATH}/spec-files-jucr/.svn ]
#parked#  then
#parked#   echo "spec-files-jucr already exists, no svn checkout done."
#parked# else
#parked#    echo "*****************"
#parked#    echo "switch user to the User-ID who stores the SVN repository."
#parked#    echo "Please enter the password for the user \"${TARGETUSERNAME}\" if prompted"
#parked#    echo ""
#parked#    echo "NOTE: please if asked to accept the ssh keys, type the word \"yes\" into the prompt svn gives to you"
#parked#    echo ""
#parked#    do_su "$JUCRSVNCHECKOUT"
#parked#fi

#spec-files checkout - note: this is the stuff used to build nome desktop on Solaris/*
echo "Solaris Desktop Software  - checking out the spec-files repository"
echo "(skipped if already exists [ -d ${SVNTARGETBASEPATH}/spec-files/.hg ] )"

if [ -d ${SVNTARGETBASEPATH}/spec-files/.hg ]
  then
   echo "spec-files already exists, no svn checkout done."
 else
    echo "*****************"
    echo "switch user to the User-ID who stores the SVN repository."
    do_su "$SPECFILESCHECKOUT"
fi


#parked##spec-files-jucr checkout
#parked#echo "JUCR - checking out the spec-files-jucr repository"

# rebuild new pkgbuild!
#SXCE:
TOOLSPREFIX=`pkgparam SFpkgbuild BASEDIR`
echo "toolsprefix >$TOOLSPREFIX<"
if [ "$TOOLSPREFIX" == "/" -o -z ""$TOOLSPREFIX ] 
  then
    echo $CBEURL | grep "jds-cbe-[0-9]"     >/dev/null && TOOLSPREFIX=/opt/jdsbld
    echo $CBEURL | grep "desktop-cbe-[0-9]" >/dev/null && TOOLSPREFIX=/opt/dtbld
    echo $CBEURL | grep "desktop-cbe-mini-[0-9]" >/dev/null && TOOLSPREFIX=/opt/dtbld
    echo "Detected jds-cbe or desktop-cbe in this location:"
    echo "  (TOOLSPREFIX) $TOOLSPREFIX=/opt/dtbld"
fi # set TOOLSPREFIX of not found by pkgparam (SVR4 package basedir)
echo "toolsprefix >$TOOLSPREFIX<"
cd "$USERTEMP"

#only works if last part is really the filename
TARGETFILENAME=$( basename $PKGBUILDURL )
/bin/rm -rf $TARGETFILENAME
wget -O $TARGETFILENAME -N -c "$PKGBUILDURL"
unset TARGETFILENAME

PKGBUILDFILE=`echo $PKGBUILDURL | sed -e 's?.*/pkgbuild-?pkgbuild-?' | sed -e 's?\.tar\.bz2.*??'`
echo "Preparing pkgbuild-version $PKGBUILDFILE"

[ -d ${PACKAGESDIR}/SOURCES ] ||  \
    case $SUPERRIGHTS in
     "pfexec"|"sudo") #tested
        ${SUPERCMD} mkdir -p ${PACKAGESDIR}/SOURCES
        ${SUPERCMD} chown -R ${TARGETUSERNAME} ${PACKAGESDIR} ${PACKAGESDIR}/SOURCES ${PACKAGESDIR}/SOURCES/pkgbuild*
        ;;
     "ssh")    #tested
        ssh -A root@localhost "mkdir -p ${PACKAGESDIR}/SOURCES; chown -R ${TARGETUSERNAME} ${PACKAGESDIR}/SOURCES ${PACKAGESDIR}/SOURCES/pkgbuild*"
        ;;
     "su")   #untested !
        echo "Please enter the password of the target userid >${TARGETUSERNAME}<"
	echo "receiving the compile environment:"
        do_su "mkdir -p ${PACKAGESDIR}/SOURCES"
        ;;
      "")  #OI2010/OI2011 or recent Solaris Express 11
        mkdir -p ${PACKAGESDIR}/SOURCES
        ;;
    esac

#some time pkgbuild comes as tar bundle we have to copy ourselfs
#problematic, if script has been run before as root, then wrong owner here
${SUPERCMD} chown ${TARGETUSERNAME} ${PACKAGESDIR} ${PACKAGESDIR}/* ${PACKAGESDIR}/SOURCES/pkgbuild*
bzcat $PKGBUILDFILE.tar.bz2  | tar xf -
patch -p0 < $USERHOMEDIR/$PKGBUILDFILE.patch
sed -ie 's/\^patch/\^GNU patch/' $PKGBUILDFILE/configure
tar cf $PKGBUILDFILE.tar $PKGBUILDFILE
rm $PKGBUILDFILE.tar.bz2
bzip2 $PKGBUILDFILE.tar
if cp -p $PKGBUILDFILE.tar.bz2 ${PACKAGESDIR}/SOURCES/
  then
   echo "Copied source of pkgbuild to the SOURCES directory"
   echo "Extracting pkgbuild.spec from the source and calling pkgbuild"
   (cd "$USERTEMP"; 
    bzip2 -d < "$USERTEMP/$PKGBUILDFILE.tar.bz2" | tar xf - "$PKGBUILDFILE/pkgbuild.spec";
    mv $PKGBUILDFILE/pkgbuild.spec $PKGBUILDFILE/pkgbuild.spec.orig
#we use in CBE and outdated pkgbuild with problems working with %doc and Meta()
    egrep -v "%\{_datadir\}|^Meta|^%doc|^IPS_Package_Name:" < $PKGBUILDFILE/pkgbuild.spec.orig > $PKGBUILDFILE/pkgbuild.spec
    #replacing the entire %files section with one that works with 
    #pkgbuild-1.3.veryold and .verynew as well
    #S12 brings a gsed with other output for --version GNU sed version 4.2.1 -> gsed (GNU sed) 4.2.2
    $EXCMD $PKGBUILDFILE/pkgbuild.spec << EOF
/%define pkgbuild_prefix
d
/%define _prefix %{pkgbuild_prefix}
d
a
%define pkgbuild_prefix %{_prefix}
.
/configure
i
gsed -i.bak_gnused -e 's/\^*GNU sed /GNU sed/' configure
chmod 775 configure
.
/^%files
.,$ d
a
#replaced entire %files section by bootstrap-sfe-latest
%files
%defattr (-, root, bin)
%attr (0755, root, bin) %{_bindir}
%attr (0755, root, bin) %{_libdir}
%dir %attr (0755, root, sys) %{_datadir}
%{_datadir}/pkgbuild/*
%dir %attr (0755, root, bin) %{_mandir}
%dir %attr (0755, root, bin) %{_mandir}/man1
%{_mandir}/man1/*
.
wq
EOF
#remove references to perl584 (we check this in bootstrap ourselves)
gsed -i.remove.perl.dependency -e 's/^.*Requires:.*perl/#perl/' $PKGBUILDFILE/pkgbuild.spec
    )
 else
   echo "Error with extracting pkgbuild.spec"
   exit 1
fi


# B I G G E S T  N O T E   E V E R !!!!
# once env.sh is sourced, you lose all the variable set in the script above. 
# so don't expect them to be usable below - unless `you` did it yourself
#stupid enough, $USERTEMP gets removed as well, so we don't have the 
#path to the file anymore

echo "saving environment variables into a file"
touch "$USERTEMP"/temp-env-storage.$$
chmod 600 "$USERTEMP"/temp-env-storage.$$
echo "TOOLSPREFIX=\"$TOOLSPREFIX\"" > "$USERTEMP"/temp-env-storage.$$
echo "CCOMPILERPATH=\"$CCOMPILERPATH\"" >> "$USERTEMP"/temp-env-storage.$$
echo "PACKAGESDIR=\"$PACKAGESDIR\"" >> "$USERTEMP"/temp-env-storage.$$
echo "PKGBUILDFILE=\"$PKGBUILDFILE\"" >> "$USERTEMP"/temp-env-storage.$$
echo "TARGETUSERNAME=\"$TARGETUSERNAME\"" >> "$USERTEMP"/temp-env-storage.$$
echo "USESU=\"$USESU\"" >> "$USERTEMP"/temp-env-storage.$$
echo "SUPERCMD=\"$SUPERCMD\"" >> "$USERTEMP"/temp-env-storage.$$
echo "SUPERRIGHTS=\"$SUPERRIGHTS\"" >> "$USERTEMP"/temp-env-storage.$$
echo "CHECKDEPSURL=\"$CHECKDEPSURL\"" >> "$USERTEMP"/temp-env-storage.$$
# paused # 
# paused # if [ -x /opt/dtbld/bin/env.sh ] 
# paused #   then 
# paused #   source /opt/dtbld/bin/env.sh default
# paused # else
# paused #   source /opt/jdsbld/bin/env.sh
# paused # fi
# paused # 
# paused # echo "restoring temprary variables from file"
# paused # eval `cat "$USERTEMP"/temp-env-storage.$$`
# paused # echo "restored: TOOLSPREFIX=\"$TOOLSPREFIX\""
# paused # echo "restored: CCOMPILERPATH=\"$CCOMPILERPATH\""
# paused # echo "restored: PACKAGESDIR=\"$PACKAGESDIR\""
# paused # echo "restored: PKGBUILDFILE=\"$PKGBUILDFILE\""
# paused # echo "restored: TARGETUSERNAME=\"$TARGETUSERNAME\""
# paused # echo "restored: USESU=\"$USESU\""
# paused # echo "restored: SUPERCMD=\"$SUPERCMD\""
# paused # echo "restored: SUPERRIGHTS=\"$SUPERRIGHTS\""
# paused # echo "restored: CHECKDEPSURL=\"$CHECKDEPSURL\""
#deleting, then using that file few lines below?
# paused # rm "$USERTEMP"/temp-env-storage.$$

#check for version of installed pkgtool and if 1.3.3, remove the lines find_in_path ('notify-send') or $defaults->set ('notify', 0);
#1.3.3,REV=2008.09.18.09.10.51
#this happens if SUNWgnome-panel is not installed on the system and binary notify-send to feed dbus messages is not in PATH nor configured in .pkgtool*
pkgparam SFpkgbuild VERSION | grep "^1.3.3," && ${SUPERCMD} perl -pi.bak -e 's?find_in_path.*notify-send.*?#?' $TOOLSPREFIX/lib/pkgbuild-1.3.3/pkgtool.pl

#prepare a compile script wich get's executed as the build user - to replace the old pkgbuild with the new (build as non-root)
cat - > "$USERTEMP"/pkgbuild-compilescript.$$ <<EOF
#!/bin/bash
if [ -x /opt/dtbld/bin/env.sh ] 
  then 
  source /opt/dtbld/bin/env.sh default
else
  source /opt/jdsbld/bin/env.sh
fi
if [ -f /opt/dtbld/bin/env_include.sh ]
   then
   source /opt/dtbld/bin/env_include.sh
fi
eval `cat "$USERTEMP"/temp-env-storage.$$`
echo "We've seen the build process below hanging sometimes (build143). Try rebooting and then re-run the bootstrap-script"
set -x
RUNPKGBUILD=/bin/false
[ -x /usr/bin/pkgtool ] && RUNPKGBUILD=/usr/bin/pkgtool
[ -x $TOOLSPREFIX/bin/pkgtool ] && RUNPKGBUILD=$TOOLSPREFIX/bin/pkgtool
export GNU_SED=/usr/bin/gsed
\$RUNPKGBUILD --download --define '_datadir '"$TOOLSPREFIX"/share --define '_prefix '"$TOOLSPREFIX" --define 'pkgbuild_prefix '"$TOOLSPREFIX"  --define '_prefix '"$TOOLSPREFIX" build-only "$USERTEMP/$PKGBUILDFILE/pkgbuild.spec"
exit \$?
EOF
chmod a+x "$USERTEMP"/pkgbuild-compilescript.$$

# not need this patch for pkgbuild-1.3.105.
##/^%setup
if echo $PKGBUILDFILE | egrep -- "104"
then
$EXCMD "$USERTEMP/$PKGBUILDFILE/pkgbuild.spec" << EOFP0
/^make
i
patch -p0 pkgbuild.pl < "$USERTEMP/$PKGBUILDFILE/pkgbuild-01-use.pkg.publish.diff"
.
w!
q
EOFP0

echo "$EXCMD editing $USERTEMP/$PKGBUILDFILE/pkgbuild.spec with result: $?"
fi

#create patch for "pkg publish"
cat > $USERTEMP/$PKGBUILDFILE/pkgbuild-01-use.pkg.publish.diff << PATCHPUBLISH
use the very much faster pkg publish method
--- pkgbuild.pl.orig.1.3.104	Sa. Okt  5 21:55:05 2013
+++ pkgbuild.pl	Sa. Okt  5 22:25:41 2013
@@ -2221,8 +2223,14 @@
     } else {
 	push (@\$ref_lines, "export PKG_REPO=\\\${PKGBUILD_IPS_SERVER:-\$ips_server}");
     }
-    push (@\$ref_lines, "eval \`pkgsend open \$name\@\$version\` || exit 1");
-    push (@\$ref_lines, "pkgsend include \$manifest || exit 2");
+    #push (@\$ref_lines, "eval \`pkgsend open \$name\@\$version\` || exit 1");
+    #push (@\$ref_lines, "pkgsend include \$manifest || exit 2");
+    push (@\$ref_lines, "mv \$manifest \$manifest.tmp || exit 1");
+    push (@\$ref_lines, "echo \"set name=pkg.fmri value=\$name\@\$version\" > \$manifest || exit 2");
+    push (@\$ref_lines, "cat \$manifest.tmp >> \$manifest || exit 3");
+    push (@\$ref_lines, "pfexec pkgsend publish \$manifest || exit 4");
+    push (@\$ref_lines, "if echo \\\$PKG_REPO | egrep \"/var/pkglocal|file://\"; then pfexec pkgrepo -s \\\$PKG_REPO refresh || exit 5; fi");
+    push (@\$ref_lines, "if echo \\\$PKG_REPO | egrep \"/var/pkglocal|file://\"; then pfexec pkg refresh \\\$LOCALPUBLISHER || exit 6; fi");
 } 
 
 # Add lincense action
@@ -2498,7 +2502,7 @@
     my \$ref_lines = shift;
     my @lines = @\$ref_lines;
     
-    push (@\$ref_lines , "pkgsend close || exit 3");
+    #push (@\$ref_lines , "pkgsend close || exit 3");
 }
 
 my @autotag_data = (["etc/gconf/schemas/.*\.(schemas|entries)",
PATCHPUBLISH

#if [ "$(/bin/bash -c \"$USERTEMP\"/pkgbuild-compilescript.$$)" ]
/bin/bash -c "$USERTEMP"/pkgbuild-compilescript.$$ > "$USERTEMP"/pkgbuild-compilescript.log.$$ 2>&1
#retpkgbuild=$?
retpkgbuild="-1"
grep "PASSED" "$USERTEMP"/pkgbuild-compilescript.log.$$ && retpkgbuild=0
if [ $retpkgbuild == 0 ] 
  then
  echo "pkgbuild succeeded, replace the old version now..."
  cat - > "$USERTEMP"/SFpkgbuild-removal.sh <<EOF
#!/usr/bin/bash
echo "trying IPS uninstall of existing pkgbuild:"
pkg uninstall pkgbuild
echo "trying SVR4 uninstall of (existing) pkgbuild"
yes | pkgrm SFpkgbuild
EOF
  chmod +x "$USERTEMP"/SFpkgbuild-removal.sh
  ${SUPERCMD} "$USERTEMP"/SFpkgbuild-removal.sh
  ${SUPERCMD} /usr/sbin/pkgadd -d ${PACKAGESDIR}/PKGS SFpkgbuild
 else
  echo "Building or installing new SFpkgbuild failed, leaving old version in place."
  echo "We are not finished yet. The errors need to be fixed. Then re-run"
  echo "this bootstrap script to get the fresh pkgbuild version."
exit 44
fi
####[ -r  "$USERTEMP"/pkgbuild-compilescript.$$ ] && rm  "$USERTEMP"/pkgbuild-compilescript.$$ 

set +x

#cd spec-files-extra
#  
#if [ -x /opt/jdsbld/bin/env.sh ] 
#  then 
#  . /opt/jdsbld/bin/env.sh
#else
#  . /opt/dtbld/bin/env.sh default
#fi
#
#if pkgtool --download build-only SFEbvi.spec
#  then
#    echo "congratulations, test-run of pkgtool --download build-only SFEbvi.spec   succeeded"
#  else
#    echo "error. pkgtool --download build-only SFEbvi.spec   did not succeed, check for error messages."
#fi


# XXX: THIS DOES NOT WORK IF THE USER HAS ONLY THE "Software Installation" PROFILE!
# add a helper script to resolve packages
  cat > $USERTEMP/resolveipspackages.$$ <<EOF
#!/usr/bin/bash
##TODO## example: pkg install SUNWruby18r fails, but pkg search -r SUNWruby18r resolves to IPS ruby package - solution? is this pkg install failing or pkgbuild not climbing down the list of compatibility/historic package names
#20090818 Thomas Wagner - install missing packages from the current package repository based on what pkgtool build-order cannot resolve
#pkgtool -v 1.3.104:
#INFO: No spec file for compatibility/packages/SUNWxwopt found.
#pkgtool -v -v 1.3.103 on OI
#INFO: Trying to find spec file for database/mysql-51/library
#INFO: Looking for database/mysql-51/library.spec

echo "\$0 from bootstrap-sfe-<latest|testing> version $VERSIONBOOTSTRAP"

MISSING=\`pkgtool -v -v build-order --autodeps \$* | egrep "(No spec)|(Looking for )" | gsed -e 's?.*No spec file for *??' -e 's?.*No spec *??' -e 's? *found\.??' -e 's?INFO: Looking for ??' -e 's?\.spec\$??'| gsed -e '/[\/]/! s/-devel\$//' -e '/[\/]/! s/-root\$//' -e '/[\/]/! s/-doc\$//' | sort -u | grep -v "SFE"\`
if echo "\$MISSING" | egrep "nothing|at least one package name required" >/dev/null
  then
   echo "Lucky you, no packages from outside the build recipe repository seem to be missing"
   exit 0
  else
   echo "Found the packages listed below to be missing, will try to install them from the"
   echo "local repository (should not hit packages from your build recipe repository)."
   echo "Watch for errors in the output."
   echo "========="
   echo "\$MISSING"
   echo "========="
   echo "The list above might be empty or not."
   echo "Now we try to automatically install missing packages by:"
   echo "pfexec pkg install -v $PKG_ACCEPT_SHOW_LICENSE \$MISSING"
   echo "Please watch out for lines indicating that packages are not found in the catalog"
   echo ""
   pfexec pkg install $PKG_ACCEPT_SHOW_LICENSE \$MISSING
   ret=\$?
   echo "Done. Exit code: \$ret"
   exit \$ret
  fi
EOF
  
  if [ -x $TOOLSPREFIX/bin/resolveipspackages ]
    then
     echo "We already have one, renaming it to .old.$$"
     ${SUPERCMD} mv $TOOLSPREFIX/bin/resolveipspackages $TOOLSPREFIX/bin/resolveipspackages.old.$$ 2> /dev/null
    fi
   ${SUPERCMD} cp "$USERTEMP"/resolveipspackages.$$ $TOOLSPREFIX/bin/resolveipspackages && rm "$USERTEMP"/resolveipspackages.$$ 2> /dev/null

   ${SUPERCMD} chmod a+rx $TOOLSPREFIX/bin/resolveipspackages 2> /dev/null

# Install the check-deps script, to make dependency checking easier.
##REVISIT## check it this still applies: # XXX: As elsewhere, this will not work properly as "Software Installation" profile.
cd $USERTEMP
wget -O check-deps $CHECKDEPSURL
${SUPERCMD} chmod 755 check-deps
${SUPERCMD} chown root check-deps 2>/dev/null
if [ -x $TOOLSPREFIX/bin/check-deps ]; then
  echo "We already have one, renaming it to .old.$$"
  ${SUPERCMD} mv $TOOLSPREFIX/bin/check-deps $TOOLSPREFIX/bin/check-deps.old.$$ 2> /dev/null
fi
${SUPERCMD} cp -p check-deps $TOOLSPREFIX/bin/check-deps

rm -f /tmp/HDjaHAUEdkjsj36aAHS_sfescmd_jskdhsks7238s.$$ 2>/dev/null # we're done with any escalation.

echo ""
echo ""
echo ""
echo ""
echo ""
echo ""
echo ""
echo "  ****************************************************************************"
echo "                    I M P O R T A N T  N O T E S  B E L O W ..."
echo "                     Don't ask if you don't read them first :)"
echo "  ****************************************************************************"
echo ""
echo ""
echo " Installation finished. Please \"source\" the build-environment by typing the"
echo " following into your login shell:"
echo ""
if [ -x /opt/dtbld/bin/env.sh ] 
  then 
   echo "      . /opt/dtbld/bin/env.sh "
else
   echo "      . /opt/jdsbld/bin/env.sh "
fi
echo ""
echo ""
echo " Test your fresh CommonBuildEnvironment by running the following commands:"
echo " (Read: see above, you need to source the env.sh script before!)"
echo ""
echo "         cd spec-files-extra "
echo "         pkgtool --download build-only SFEbvi.spec"
echo "         (or to really install:  pkgtool --download --svr4 build SFEbvi.spec)"
echo "         (leave out the --svr4 if you already have a local IPS server ready and"
echo "          set read/write)"
echo ""
echo "         To get prerequisite packages build automatically in the correct order,"
echo "         then use:  pkgtool --autodeps --download build SFEbvi.spec"
echo "         (note: \"build-only\" does not make sense in that --autodeps case!)"
echo ""
echo "         You may want to autoinstall prerequisite OS packages with:"
echo "         resolveipspackages SFEbvi.spec"
echo ""
echo ""
echo ""

export DETECT_WARNING=0
echo "You might need some manual manipulation of your system."
echo "This is outside the scope of this script at the moment, so please carefully"
echo "check the following items:"
echo ""
echo "Checking compiler configuration..."
if [ -L /usr/gnu/bin/cc ] && [ "$( ls -l /usr/gnu/bin/cc | grep -- "-> ../../sfw/bin/gcc" )" ]
   then
    echo ""
    echo " Issue: /usr/gnu/bin/cc symlinks to gcc compiler, interfering with the Sun"
    echo " Compiler which are both named cc."
    echo " ------------------------------------------------------------------------------"
    echo "  You have the original OpenSolaris symlink in /usr/gnu/bin/cc pointing to"
    echo "  ../../sfw/bin/gcc which in rare cases confuses automatic compiler detection"
    echo "  by configure scripts. Depending of your \"PATH\"-Settings, it will mask the"
    echo "  SunStudio Compilers with the same name \"cc\" if they appear later in the"
    echo "  search \"PATH\". "
    echo ""
    echo "  You should really consider renaming this link with this command:"
    echo ""
    echo "          ${SUPERRIGHTS} mv /usr/gnu/bin/cc /usr/gnu/bin/gcc "
    echo ""
    echo "          then re-run this script to let CBE re-do the search for compilers"
    echo ""
    echo "  Remember to check this link if you upgrade your system, the link may reappear"
    echo "  with a new version of the package SUNWgcc@3.4.3 ."
    echo "  if you run \"pkg fix SUNWgcc\" this link re-appears as well. You know what to"
    echo "  do in that case."
    echo ""
    echo "  If you re-run this bootstrap-script, this notice will be displayed again if"
    echo "  you (or a future bootstrap-script) have not corrected this issue."
    echo ""
    echo " Read: the script will *not* modify the above symlink at this time. YOU have to"
    echo " decide to move the named symlink out of the way."
    echo " Read: the above link was not present in SXCE (and Solaris 10), OpenSolaris/IPS"
    echo " tries to provide a GNU-style environment with this."
    echo ""
    export DETECT_WARNING=1
fi # /usr/gnu/bin/cc symlink

echo "Checking system privileges..."
if [[ ! $( grep "Software Installation:.*:/usr/bin/pkg:uid=0" /etc/security/exec_attr /etc/security/exec_attr.d/package* ) ]]; then
	echo ""
	echo " Issue: missing privilege to use \"pkg\" to install packages:"
        echo " ------------------------------------------------------------------------------"
	echo " "
	echo " The result: insufficient privileges to install packages"
	echo " "
	echo " Occurs if you use some builds of the \"/dev\" builds and the profile"
	echo " \"Software Installation\" is assigned."
	echo " "
	echo " On a /dev build it might be the case that the profile \"Software Installation\""
	echo " does not give the right to use \"pkg\" for installing packages (hey, wasn't it"
	echo " your intention to do just that?)."
	echo " This problem started with builds around 12x (125 or so)."
	echo " There is a fix was posted as a webrev, so some later builds were fixed."
	echo " "
	echo " Solution (temporary): Add to the file /etc/security/exec_attr this line:"
        echo " (more recent osbuilds use the files in /etc/security/exec_attr.d/***) "
	echo " "
	echo "Software Installation:suser:cmd:::/usr/sbin/pkg:uid=0 "
	echo " "
    export DETECT_WARNING=1
fi # privs/exec_attr

echo "Detecting repository settings..."
if [ "$( svcs -v application/pkg/server | /usr/xpg4/bin/awk 'RS=" " NR==2 {print $1}' )" == "disabled" ]; then
	echo " "
	echo " Issue: local package server is not started/initialized"
        echo " ------------------------------------------------------------------------------"
	echo " "
	echo " The result: pkgbuild runs fine, but you cannot send the packages to your"
	echo " local pkg repository"
	echo " "
	echo " Occurs only if you have a really fresh system where a local package server was"
	echo " never enabled by someone (that's you?)."
	echo " You may skip this step, if you are certain that your local package server"
	echo " is already running properly."
	echo " "
	echo " Check for enabled/online with: \"svcs -v application/pkg/server\" "
	echo " "
	echo " Solution: enable your local package server now and refresh the catalog"
	echo "     (taken from and read more on:"
	echo "     https://sourceforge.net/apps/mediawiki/pkgbuild/index.php?title=Pkgbuild_on_OpenSolaris#Image_Packaging_System"
	echo "     )"
	echo " "
	echo " "
	echo " Note: Run these commands as privileged user! You may use:   ${SUPERRIGHTS} bash"
	echo " "
	echo " "
	echo " All builds:"
	echo " # Create separate filesystem (optional, this is an example, use your preferred path):"
	echo "  ${SUPERRIGHTS} zfs create -p -o mountpoint=/var/pkglocal rpool/pkglocal"
	echo "  ${SUPERRIGHTS} /usr/sbin/svccfg -s application/pkg/server setprop pkg/inst_root=/var/pkglocal"
        echo " #  (note: the line below might fail on older OS builds, normally not a problem)"
	echo "  ${SUPERRIGHTS} /usr/sbin/svccfg -s pkg/server setprop pkg/inst_root = /var/pkglocal"
	echo " "
	echo " # Beginning from build 127 and newer: (older builds skip this step)"
	echo "  ${SUPERRIGHTS} pkgrepo create --version 4 /var/pkglocal"
	echo "  ${SUPERRIGHTS} pkgsend -s file:///var/pkglocal create-repository \\"
	echo "                    --set-property publisher.prefix=localhost"
	echo " "
	echo " "
	echo " "
	echo " # Continue, all builds: (note: pkg/readonly is available with new pkg server versions only)"
	echo "  ${SUPERRIGHTS} /usr/sbin/svccfg -s pkg/server setprop pkg/port=10000"
	echo "  ${SUPERRIGHTS} /usr/sbin/svccfg -s svc:/application/pkg/server setprop pkg/readonly = false"
	echo "  ${SUPERRIGHTS} /usr/sbin/svcadm refresh pkg/server"
	echo "  ${SUPERRIGHTS} /usr/sbin/svcadm enable -s pkg/server"
	echo "  ${SUPERRIGHTS} /usr/sbin/svcadm restart pkg/server # for reloading config, if it's already enabled"
	echo "  sleep 5                  # wait a few seconds for things to settle down"
	echo "  #note: publishing with unlimited file-size is only possible file://-based"
	echo "  $SUPERRIGHTS pkg set-publisher -G '*' -g file:///var/pkglocal localhost"
	echo "  #(else, not recommended, max 100MB files: $SUPERRIGHTS pkg set-publisher -G '*' -g http://localhost:10000 localhost )"
	echo " "
	echo "  $SUPERRIGHTS pkg rebuild-index"
	echo " "
	echo " please check /etc/security for sufficient rights to operate on pkg repositories."
	echo " Solaris 12 (11)
      /etc/security/exec_attr.d/package:pkg
Software Installation:solaris:cmd:::/usr/bin/pkgrepo:uid=0
Software Installation:solaris:cmd:::/usr/bin/pkgsend:uid=0
Software Installation:solaris:cmd:::/usr/bin/pkgrecv:uid=0
"
	echo " "
	echo " OpenIndiana (e.g. oi 151a8"
echo "
      /etc/security/exec_attr:
Software Installation:solaris:cmd:::/usr/bin/pkgrepo:uid=0
Software Installation:solaris:cmd:::/usr/bin/pkgsend:uid=0
Software Installation:solaris:cmd:::/usr/bin/pkgrecv:uid=0
"
	echo " "
	echo " "
    export DETECT_WARNING=1
fi # repository settings

if [ $DETECT_WARNING -eq 0 ]; then
	echo " "
	echo " Your system appears to be perfectly configured for use! Congratulations!"
	echo " Please stay advised of anything you need to know by searching the web for"
	echo " bootstrap-sfe-latest-os20nn or by the twitter search tag #SFE"
else
	echo " "
	echo " I will post these kind of issues on a small blog/wiki some day in the near"
	echo " future. Watch out by searching the web for bootstrap-sfe-latest-os20nn and"
	echo " on twitter the search-tag is #SFE"
fi # warning detection

echo " "
echo " Some instructional messages may have scrolled off screen. Please scroll up"
echo " and review them now."
echo " "
echo " Thank you for using \"bootstrap-sfe-latest-os20nn\" to improve your experience"
echo " with OpenSolaris (last build 134, discontinued), Solaris 11 Express or OpenIndiana!"

echo " If you like that script, please drop me a note by email tom68 at users.sourceforge.net "
echo " in english, german, french or your mother language."
echo " "
echo " You've read the above important information? Yes, you are a good one! :)"

exit 0

#%Changelog
#* Mon Jun  1 2015
#- Ready for OmniOS r151014
#* Min Oct  6 2014
#- add system/header for IPS > build 168, S12
#* Sun May 11 2014
#- add "-v" to pkg install in resolveipspackages
#* Sun Mar 23 2014
#- add exit $ret to resolveipspackages
#* Wed Mar 19 2014
#- make pkgsend use the content of $PKG_REPO
#* Mon Jan 06 2014
#- cosmetic fix script name displayed in resolveipspackages
#* Fri Jan 03 2014
#- fix wrong shell code in pkgbuild patch, case PKGBUILD_IPS_SERVER causes exit 5