#!/bin/sh 

# Copyright  2005 Sun Microsystems, Inc.  All rights reserved.
#
# Sun Microsystems, Inc. has intellectual property rights relating to
# technology embodied in the product that is described in this document.
# In particular, and without limitation, these intellectual property rights
# may include one or more of the U.S. patents listed at
# http://www.sun.com/patents and one or more additional patents or pending
# patent applications in the U.S. and in other countries.
#
# U.S. Government Rights - Commercial software.  Government users are subject
# to the Sun Microsystems, Inc. standard license agreement and applicable
# provisions of the FAR and its supplements.
#
# Use is subject to license terms.
#
# This distribution may include materials developed by third parties.Sun,
# Sun Microsystems and  the Sun logo are trademarks or registered trademarks
# of Sun Microsystems, Inc. in the U.S. and other countries.  
#
# Copyright  2005 Sun Microsystems, Inc. Tous droits rservs.
# Sun Microsystems, Inc. dtient les droits de proprit intellectuels relatifs
#  la technologie incorpore dans le produit qui est dcrit dans ce document.
# En particulier, et ce sans limitation, ces droits de proprit
# intellectuelle peuvent inclure un ou plus des brevets amricains lists
#  l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires
# ou les applications de brevet en attente aux Etats - Unis et dans les
# autres pays.
#
# L'utilisation est soumise aux termes du contrat de licence.
#
# Cette distribution peut comprendre des composants dvelopps par des
# tierces parties.
#
# Sun,  Sun Microsystems et  le logo Sun sont des marques de fabrique ou des
# marques dposes de Sun Microsystems, Inc. aux Etats-Unis et dans
# d'autres pays.

# amconfigupdate script updates the properties in AMConfig.properties and
# policies in server.policy file. This is for updates AM 6.2 , AM 6.3
# files

DEF_UMASK=022
PATH=/bin:/usr/bin:/sbin:/usr/sbin
OS=`uname`
if [ $OS = "Linux" ]; then
    GREP=/bin/grep
    ECHO="/bin/echo"
    RM=/bin/rm
    CONFIG_DIR=/etc/opt/sun/identity/config
    SED=/bin/sed
    MV=/bin/mv
    AWK=/usr/bin/awk
    ED=/bin/ed
    CP="/bin/cp -p"
    IS_INSTALL_VARDIR="\/var\/opt\/sun\/identity"
    MOBILEACCESS_PKG=sun-mobileaccess
    RPM=/bin/rpm
else
    GREP=/usr/bin/grep
    ECHO=/usr/bin/echo
    RM=/usr/bin/rm
    CONFIG_DIR=/etc/opt/SUNWam/config
    SED=/usr/bin/sed
    MV=/usr/bin/mv
    AWK=/usr/bin/awk
    ED=/usr/bin/ed
    CP="/usr/bin/cp -p"
    IS_INSTALL_VARDIR="\/var\/opt\/SUNWam"
    MOBILEACCESS_PKG=SUNWma
    PKGINFO=/usr/bin/pkginfo
fi

MOBILE_ACCESS_FILENAME="mobile_services.jar"

getMobileAccessFilePath() 
{
    if [ "$OS" = "Linux" ]; then
        filepath="`rpm -ql $MOBILEACCESS_PKG | $GREP $MOBILE_ACCESS_FILENAME$`"
    else 
        filepath="`/usr/sbin/pkgchk -v $MOBILEACCESS_PKG 2>&1 | $GREP $MOBILE_ACCESS_FILENAME$`"
     fi
     MOBILE_ACCESS_PKG_DIR=`echo $filepath | sed -e "s#/mobile_services.jar##g"`
     export MOBILE_ACCESS_PKG_DIR 
}

### inserts line in a file
insert_line() {
  file=$1
  match=$2
  new=$3

  if [ ! -f $file-orig-$$ ]; then
	if [ -f $file ]; then
	$CP $file $file-orig-$$
	fi
  fi

  $SED -e "
/$match/ {
i\\
$new
}" $file > $file-tmp
$CP $file-tmp $file
$RM -f $file-tmp
}


### replaces a line in a file.
replace_line() {
  file=$1
  match=$2
  new=$3

  if [ ! -f $file-orig-$$ ]; then
	if [ -f $file ]; then
	$CP $file $file-orig-$$
	fi
  fi

  $SED -e "
/$match/ {
c\\
$new
}" $file > $file-tmp
$CP $file-tmp $file
$RM -f $file-tmp
}

### AMConfig.properties changes for new properties in AM 6.2 / 6.3
### values of some attributes were changed.
filelist="$CONFIG_DIR/AMConfig.properties.template $CONFIG_DIR/AMConfig.properties"
export filelist

update_properties() {
     ### check if this is sdk install only
     $ECHO "Updating $CONFIG_DIR/AMConfig.properties ..."
     for file in $filelist 
     do
	 ## update stat properties
	 replace_line $file "com.iplanet.am.stats.interval=3600" "com.iplanet.am.stats.interval=60"

         replace_line $file "com.iplanet.services.stats.state=off" "com.iplanet.services.stats.state=file"

	 replace_line $file "com.iplanet.services.stats.directory=${IS_INSTALL_VARDIR}\/debug"  "com.iplanet.services.stats.directory=${IS_INSTALL_VARDIR}\/stats" 

	 replace_line $file "com.iplanet.services.stats.directory=IS_INSTALL_VARDIR\/IS_PRODNAME\/debug"  "com.iplanet.services.stats.directory=IS_INSTALL_VARDIR\/IS_PRODNAME\/stats" 
	
	 ## add special users if not present 
         temp=`$GREP "com.sun.identity.authentication.special.users" $file`
	if [ "$temp" = "" ]; then
	    $ECHO "" >> $file
	    $ECHO "/**" >> $file
	    $ECHO "* Identifies the special user(s) for this Sun Java System Access Manager -" >> $file
 	    $ECHO "* Authentication component. This user is used by the Remote (Client) SDK to" >> $file
	    $ECHO "* authenticate remote Applications to the Access Manager server using as the full" >> $file
	    $ECHO "* user DN. The user will always be authenticated against the local directory server.">> $file
	    $ECHO " * Multiple values of this special user DN are separated by \"|\".">> $file
	    $ECHO "* NOTE : Usage of this property is restricted to Authentication component only." >> $file
	    $ECHO "*/" >> $file
 	    $ECHO "com.sun.identity.authentication.special.users=cn=dsameuser,ou=DSAME Users,ORG_BASE|cn=amService-UrlAccessAgent,ou=DSAME Users,ORG_BASE/" >> $file
	else
	     ### update authentication special users
             $SED -e "/^com.sun.identity.authentication.special.users/ s/$/|cn=amService-UrlAccessAgent,ou=DSAME Users,ORG_BASE/" $file > $file+

	     $MV $file+ $file
	fi

	 ### for AM 6.2 to AM 7.0 upgrade following properties are needed.
	
	temp=`$GREP "Identity Server" $file`
	if [ "$temp" != "" ]; then
	    $SED -e "s/Identity Server/Access Manager/g" $file > $file+
	    $MV $file+ $file
	fi
	temp=`$GREP " IS " $file`
	if [ "$temp" != "" ]; then
	    $SED -e "s/ IS /Access Manager/g" $file > $file+
	    $MV $file+ $file
	fi
	 ### update namespacePrefixMappingList

         temp=`$GREP "is=urn:liberty:is:2003-08" $file`
         if [ "$temp" = "" ]; then
             $SED -e "/^com.sun.identity.liberty.ws.jaxb.namespacePrefixMappingList/ s/$/|is=urn:liberty:is:2003-08/" $file > $file+
             $MV $file+ $file
	 fi

### add event properties
	temp=`$GREP "com.sun.am.event.connection.idle.timeout" $file`
	if [ "$temp" = "" ]; then
	    $ECHO "" >> $file
	    $ECHO "/**" >> $file
	    $ECHO "* The following properties can be used when a Load Balancer/Firewall" >> $file
	    $ECHO "* is in between the agents and the Directory Server and the persistent" >> $file
	    $ECHO "* search connections are dropped by them when TCP idle timeout happens.  " >> $file
	    $ECHO "*" >> $file
	    $ECHO "* These properties make sure that the persistent searches restart" >> $file
	    $ECHO "* in such cases when the connections are dropped." >> $file
	    $ECHO "*" >> $file
	    $ECHO "* The property 'com.sun.am.event.connection.idle.timeout' specifies" >> $file
	    $ECHO "* timeout value in minutes after which the persistent searches will be" >> $file
	    $ECHO "* restarted. Ideally, this value should be lower than the Load Balancer/" >> $file
	    $ECHO "* Firewall TCP timeout, to make sure that the persistent searches are" >> $file
	    $ECHO "* restarted before the connections are dropped. A value of '0' indicates" >> $file
	    $ECHO "* that these searches will not be restarted. By default the value is '0'" >> $file
	    $ECHO "* The property 'com.sun.am.event.poll.sleep.time' specifies the sleep time" >> $file
	    $ECHO "* in milliseconds after which persistent search idle timeout is checked." >> $file
	    $ECHO " */" >> $file
	    $ECHO "com.sun.am.event.connection.idle.timeout=0" >> $file
	    $ECHO "com.sun.am.event.poll.sleep.time=10000" >> $file
	    $ECHO "" >> $file
	fi
	
###
	temp=`$GREP "com.sun.identity.federation.proxyfinder" $file`
	if [ "$temp" = "" ]; then
	    $ECHO "" >> $file
	    $ECHO "# This property defines the implementation for finding a preferred identity" >> $file
	    $ECHO "# provider to be proxied" >> $file
	    $ECHO "com.sun.identity.federation.proxyfinder=com.sun.identity.federation.services.FSIDPProxyImpl" >> $file
	    $ECHO "" >> $file
	fi 
###

	temp=`$GREP "com.sun.identity.policy.client.booleanActionValues" $file`
	if [ "$temp" = "" ]; then
	    $ECHO "" >> $file
	    $ECHO "#com.sun.identity.policy.client properties added in 6.3" >> $file
	    $ECHO "#" >> $file
	    $ECHO "# boolean action values for policy action names" >> $file
	    $ECHO "#format is serviceName|actionName|trueValue|falseValue" >> $file
	    $ECHO "#Values for different action names should be delimited by :" >> $file
	    $ECHO "com.sun.identity.policy.client.booleanActionValues=iPlanetAMWebAgentService|GET|allow|deny:iPlanetAMWebAgentService|POST|allow|deny" >> $file
	    $ECHO "" >> $file
	fi

	temp=`$GREP "com.sun.identity.policy.client.resourceComparators=" $file`
	if [ "$temp" = "" ]; then
	    $ECHO "" >> $file
	    $ECHO "# ResourceComparators to be used for different service names" >> $file
	    $ECHO "#Copy value from Access Manager- Service Configuration>PolicyConfiguration>Global:ResourceComparator" >> $file
	    $ECHO "#Concatenate multiple values from Access Manager using : as delimiter" >> $file
	    $ECHO "com.sun.identity.policy.client.resourceComparators=serviceType=iPlanetAMWebAgentService|class=com.sun.identity.policy.plugins.URLResourceName|wildcard=*|delimiter=/|caseSensitive=true" >> $file
	    $ECHO "" >> $file
	fi

	temp=`$GREP "com.sun.identity.policy.client.cacheMode" $file`
	if [ "$temp" = "" ]; then
	    $ECHO "" >> $file
	    $ECHO "#cache mode for client policy evaluator" >> $file
	    $ECHO "#valid values: subtree | self" >> $file
	    $ECHO "#if cacheMode is set to subtree, policy evaluator eagerly gets policy decisions" >> $file
	    $ECHO "#from the server for all the resources from the root of resource actually requested" >> $file
	    $ECHO "#" >> $file
	    $ECHO "#if cacheMode is set to self, policy evaluator gets policy decision" >> $file
	    $ECHO "#from the server just for the resource actually requested" >> $file
	    $ECHO "com.sun.identity.policy.client.cacheMode=self" >> $file
	    $ECHO "" >> $file
	fi
####

	temp=`$GREP "#com.sun.identity.policy.client.clockSkew=10" $file`
	if [ "$temp" = "" ]; then
	    $ECHO "" >> $file
	    $ECHO "#property to adjust for time difference between" >> $file
	    $ECHO "#policy client machine and policy server." >> $file
	    $ECHO "#In the absence of this property and where agent time differs" >> $file
	    $ECHO "#from server time you would occassionally see incorrect policy decision" >> $file
	    $ECHO "#you would still need to run a time syncing service to keep the time" >> $file
	    $ECHO "#on policy server and policy client as close as possible" >> $file
	    $ECHO "#use this property to adjust for the small time difference" >> $file
	    $ECHO "#in spite of running time syncing service" >> $file
	    $ECHO "#clock skew in seconds = agentTime - serverTime" >> $file
	    $ECHO "#leave it commented out on policy server" >> $file
	    $ECHO "#uncomment the line and set appropriate value on policy client machine" >> $file
	    $ECHO "#or the machine running policy agent" >> $file
	    $ECHO "#agent-server clock skew in seconds" >> $file
	    $ECHO "#com.sun.identity.policy.client.clockSkew=10" >> $file
	$ECHO "" >> $file
       fi

	temp=`$GREP "com.sun.identity.auth.cookieName" $file`
	if [ "$temp" = "" ]; then
	    $ECHO "" >> $file
	    $ECHO " ## Authentication Cookie Name. This cookie name is used by" >> $file
	    $ECHO "## authentication service during the authentication process." >> $file
	    $ECHO "com.sun.identity.auth.cookieName=AMAuthCookie" >> $file
	    $ECHO "" >> $file
	fi


	###
	$ECHO "" >> $file
	$ECHO "com.iplanet.am.jssproxy.SSLTrustHostList=" >> $file
	$ECHO "" >> $file
	$ECHO "## Set it 'true', if LDAPProxy is supported by the backend storage" >> $file
	$ECHO "## so if true, use Proxy for connection" >> $file
	$ECHO "## If false, no proxy is used for connection." >> $file
	$ECHO "com.sun.identity.sm.ldap.enableProxy=true" >> $file

	###
       TEMP=`$GREP "com.sun.identity.liberty.ws.ta.certalias=" $file | $SED -e 's/com.sun.identity.liberty.ws.ta.certalias=//'`
       echo $TEMP
       insert_line $file "sun.identity.liberty.ws.security.TokenProviderImpl=" "com.sun.identity.liberty.ws.trustedca.certaliases=$TEMP"

       insert_line $file "com.sun.identity.liberty.ws.security.TokenProviderImpl specifies" " * com.sun.identity.liberty.ws.trustedca.certaliases specifies certificate"

       insert_line $file "com.sun.identity.liberty.ws.security.TokenProviderImpl specifies" " *	aliases for trusted CA. SAML or SAML BEARER token of incoming request"

       insert_line $file "com.sun.identity.liberty.ws.security.TokenProviderImpl specifies" " *	message needs to be signed by a trusted CA in this list. Multiple values"

       insert_line $file "com.sun.identity.liberty.ws.security.TokenProviderImpl specifies" " *	should be separated by \"|\""

    done
}

get_am_version() {

    file="$CONFIG_DIR/AMConfig.properties"
    if [ -f $file ]; then
        temp=`$GREP "com.iplanet.am.version=7 2005Q4" $file`
	if [ "$temp" = "" ]; then
	    retVal=0
	else
	    retVal=1
	fi
    fi
	export retVal
}

update_version() {
    file="$CONFIG_DIR/AMConfig.properties"
    $SED -e "/^com.iplanet.am.version=/ s/=.*$/=DPRO_VERSION/" $file > $file+
    $MV $file+ $file
}

### updating container policy files
### Currently we have changes only for AS 81
### 
update_container_policies() {
  if [ "$WEB_CONTAINER" = "WS6" ]; then
    POLICY_FILE="${WS61_HOME}/${WS61_INSTANCE}/config/server.policy"
  elif [ "$WEB_CONTAINER" = "WL8" ]; then
    POLICY_FILE="$WL8_INSTANCE/server/lib/weblogic.policy"
  elif [ "$WEB_CONTAINER" = "WAS5" ]; then
    POLICY_FILE="$WAS51_HOME/properties/server.policy"
  elif [ "$WEB_CONTAINER" = "AS8" ]; then
    POLICY_FILE="${AS81_INSTANCE_DIR}/config/server.policy"
  fi

  export POLICY_FILE


  if [ -f $POLICY_FILE ] && [ $WEB_CONTAINER = "AS8" ]; then
        $ECHO "Updating $WEB_CONTAINER policy file $POLICY_FILE..."
	temp=`$GREP "permission javax.net.ssl.SSLPermission \"setHostnameVerifier\"" $POLICY_FILE`
	if [ "$temp" = "" ]; then
	    $AWK '{print}/permission javax.security.auth.kerberos.ServicePermission/{printf "    permission javax.net.ssl.SSLPermission \"setHostnameVerifier\";\n"}' $POLICY_FILE > $POLICY_FILE+
            $MV $POLICY_FILE+ $POLICY_FILE
        fi 

    $ED $POLICY_FILE <<EOF 2>&1 > /dev/null
/permission javax.net.ssl.SSLPermission
+
i
    permission java.security.SecurityPermission "putProviderProperty.IAIK";
    permission java.security.SecurityPermission "removeProvider.IAIK";
    permission java.security.SecurityPermission "insertProvider.IAIK";
.
w
q
EOF

	temp=`$GREP "permission java.util.PropertyPermission \"user.language\", \"write\";" $POLICY_FILE`
	if [ "$temp" = "" ]; then
	    $AWK '{print}/permission javax.security.auth.kerberos.ServicePermission/{printf "    permission java.util.PropertyPermission \"user.language\", \"write\";\n"}' $POLICY_FILE > $POLICY_FILE+
	    $MV $POLICY_FILE+ $POLICY_FILE
	fi

	$AWK '{print}/am_sdk.jar/{printf "	permission java.util.PropertyPermission \"*\", \"read, write\";\n"}' $POLICY_FILE > $POLICY_FILE+
	if [ -f $POLICY_FILE+ ]; then
	    $MV $POLICY_FILE+ $POLICY_FILE
	fi

	$AWK '{print}/am_services.jar/{printf "\tpermission java.util.PropertyPermission \"*\", \"read, write\";\n"}' $POLICY_FILE > $POLICY_FILE+

	if [ -f $POLICY_FILE+ ]; then
    	    $MV $POLICY_FILE+ $POLICY_FILE
	fi

	$AWK '{print}/amserver/{printf "\tpermission java.util.PropertyPermission \"*\", \"read, write\";\n"}' $POLICY_FILE > $POLICY_FILE+

	if [ -f $POLICY_FILE+ ]; then
	    $MV $POLICY_FILE+ $POLICY_FILE
	fi

	getMobileAccessFilePath
cat << EOF >> $POLICY_FILE

    grant codeBase "file:\${com.sun.aas.instanceRoot}/applications/j2ee-modules/amconsole/-" {
	permission java.net.SocketPermission "*", "connect,accept,resolve";
	permission java.util.PropertyPermission "*", "read, write";
    };
    grant codeBase "file:\${com.sun.aas.instanceRoot}/applications/j2ee-modules/ampassword/-" {
	permission java.net.SocketPermission "*", "connect,accept,resolve";
	permission java.util.PropertyPermission "*", "read, write";
    };
    grant codeBase "file:${MOBILE_ACCESS_PKG_DIR}/-" {
      permission java.net.SocketPermission "*", "connect,accept,resolve";
      permission java.util.PropertyPermission "*", "read, write";
    };
    grant codeBase "file:${PKGDIR}/lib/swec.jar" {
        permission java.security.AllPermission;
    };
EOF
   fi ### container check end
}

get_orig_config_file() {

if [ "$OS" = "Linux" ]; then
        $RPM -q sun-identity-services > /tmp/.pkg.tmp
        if [ "$?" -ne "0" ]; then
            restoreAMConfig="true"
        fi
     else
         $PKGINFO -q SUNWamsvc > /tmp/.pkg.tmp
        if [ "$?" -ne "0" ]; then
            restoreAMConfig="true"
        fi
     fi

     if [ "$restoreAMConfig" = "true" ]; then
            $CP $CONFIG_DIR/.AMConfig.properties.bak $CONFIG_DIR/AMConfig.properties
            $CP $CONFIG_DIR/.serverconfig.xml.bak $CONFIG_DIR/serverconfig.xml
            filelist="$CONFIG_DIR/AMConfig.properties"
	    export filelist
     fi
     $RM /tmp/.pkg.tmp
}
######################################################################## 
#########Main
######################################################################## 
    	    
SAMPLE_SILENT_FILE=$1
if [ "$SAMPLE_SILENT_FILE" = "" ]; then
    exit 1
fi

. $SAMPLE_SILENT_FILE
get_orig_config_file
get_am_version
## If version is not AM 7.0 then
## update
if [ "$retVal" =  "0" ]; then
    update_properties
    update_container_policies 
else
    exit 1
fi

update_version
exit 0
