#!/bin/sh

# $Id: saml2util,v 1.34 2006/04/26 17:38:08 qcheng Exp $
# Copyright  2006 Sun Microsystems, Inc. All rights reserved.
# 
# SUN PROPRIETARY/CONFIDENTIAL.
# 
# 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. Sun, Sun Microsystems, the Sun logo and Java
# are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S.
# and other countries. All SPARC trademarks are used under license and are
# trademarks or registered trademarks of SPARC International, Inc. in the U.S.
# and other countries.
# 
# UNIX is a registered trademark in the U.S. and other countries, exclusively
# licensed through X/Open Company, Ltd.
# 
# Copyright  2006 Sun Microsystems, Inc. Tous droits rservs.
# 
# Proprit de SUN/CONFIDENTIEL.
# 
# L'utilisation est soumise aux termes du contrat de licence.Sun, Sun
# Microsystems, le logo Sun et Java sont des marques de fabrique ou des marques
# dposes de Sun Microsystems, Inc. aux Etats-Unis et dans d'autres pays.
# 
# Toutes les marques SPARC sont utilises sous licence et sont des marques de
# fabrique ou des marques dposes de SPARC International, Inc. aux Etats-Unis
# et dans d'autres pays.
# 
# UNIX est une marque dpose aux Etats-Unis et dans d'autres pays et licencie
# exlusivement par X/Open Company, Ltd.

SED=/bin/sed
ECHO=/bin/echo
OMIT='\c'
CP=/bin/cp
RM=/bin/rm

pdir=`dirname $0`
CURR_DIR=`pwd`

# private utilities
validateResponse()
{
    ok="no"

    question=$1
    default=$2

    valids="ynYN"
    while [ "$ok" = "no" ]
    do
        if [ "$default" = "y" ] || [ "$default" = "Y" ]; then
            $ECHO
            $ECHO "$question [y]/n: ${OMIT}"
            default="y"
        elif [ "$default" = "n" ] || [ "$default" = "N" ]; then
            $ECHO
            $ECHO "$question y/[n]: ${OMIT}"
            default="n"
        else
            $ECHO
            $ECHO "$question y/n: ${OMIT}"
            default=""
        fi
        read ans

        if [ "$ans" = "" ]; then
            if [ "$default" != "" ]; then
                ans=$default
            fi
        fi

        if [ "$ans" = "y" ] || [ "$ans" = "Y" ] || [ "$ans" = "N" ] || [ "$ans" = "n" ]; then
            ok="yes"
        fi

        if [ "$ok" = "no" ]; then
            $ECHO
            $ECHO "Invalid response!"
            $ECHO
        fi
    done

    # make sure we have a std response so client doesn't need to check
    if [ "$ans" = "Y" ]; then
        ans="y"
    elif [ "$ans" = "N" ]; then
        ans="n"
    fi
}

cleanUpAll()
{
displayMessage "Removing SAML2 packages ..."
if [ "$OS" = "SunOS" ]; then
ADMIN=/tmp/rmpkgadmin
echo "action=nocheck" > $ADMIN
echo "idepend=nocheck" >> $ADMIN
echo "rdepend=nocheck" >> $ADMIN
echo "space=nocheck" >> $ADMIN
echo "mail=" >> $ADMIN
pkgrm -A -n -a $ADMIN SUNWsaml2 > $saml2_log 2>&1
else
rpm -e sun-saml2
fi
}

CreateWarFile() {
    if [ "$SYSTEM" = "FM" ]; then
	cd $STAGING_DIR/web-src; $JAVA_HOME/bin/jar cf ${CURRENT_WAR_FILE} * 1>>$saml2_log 2>&1
    else
	cd $STAGING_DIR; $JAVA_HOME/bin/jar cf ${CURRENT_WAR_FILE} * 1>>$saml2_log 2>&1
    fi
    if [ $? -ne 0 ]; then
	displayMessage "Creation of war file failed. Check log file for details at: $saml2_log"
    else
	displayMessage "The new $SYSTEM server war ${CURRENT_WAR_FILE} is ready for deploy!"
    fi
}


cleanup_and_exit() {
    exit 1
}

tagSwap()
{
   for f in $EDIT_FILES; do
      $CP $f $f+
      sed -e "s#XML_ENCODING#$encoding#g" \
	  -e "s#SERVER_DEPLOY_URI#$SERVER_DEPLOY_URI#g" \
	  -e "s#DEPLOY_URI#$DEPLOY_URI#g" \
	  -e "s#IS_INSTALL_VARDIR#/var$BASEDIR#g" \
	  -e "s#IS_PRODNAME#$PRODUCT_DIR#g" \
	  -e "s#COOKIE_DOMAIN#$COMMON_COOKIE_DOMAIN#g" \
	  -e "s#COOKIE_ENCODE#$COOKIE_ENCODE#g" \
	  -e "s#ROOT_SUFFIX#$defaultOrg#g" \
	  -e "s#BASEDIR#$BASEDIR#g" \
	  -e "s#PRODUCT_DIR#$PRODUCT_DIR#g" \
	$f+ > $f
      $RM $f+
   done
}

LoadServices() {

 EDIT_FILES="`/bin/ls -1 $BASEDIR/$PRODUCT_DIR/saml2/config/xml/*.xml $BASEDIR/$PRODUCT_DIR/saml2/bin/saml2bulkfed`"
 tagSwap
 servicexmls="$BASEDIR/$PRODUCT_DIR/saml2/config/xml/amAuthSAML2.xml \
	      $BASEDIR/$PRODUCT_DIR/saml2/config/xml/fmSAML2.xml \
	      $BASEDIR/$PRODUCT_DIR/saml2/config/xml/saml2COTConfig.xml"

 SDS_INDEX="$BASEDIR/$PRODUCT_DIR/saml2/config/ldif/saml2_sds_index.ldif"
 SDS_SCHEMA="$BASEDIR/$PRODUCT_DIR/saml2/config/ldif/saml2_sds_schema.ldif"
 AD_SCHEMA="$BASEDIR/$PRODUCT_DIR/saml2/config/ldif/saml2_ad_schema.ldif"
 SAML2MODULEADD="$BASEDIR/$PRODUCT_DIR/saml2/config/xml/saml2_module_add.xml"
 if [ "$SYSTEM" = "AM" ]; then
    $amadmin -u amadmin -f "$FILE_ADMINPASSWD" -t $SAML2MODULEADD 1>>$saml2_log 2>&1
    $amadmin -u amadmin -f "$FILE_ADMINPASSWD" -s ${servicexmls} 1>>$saml2_log 2>&1
 else
    $amadmin -i ${STAGING_DIR} -u amadmin -f "$FILE_ADMINPASSWD" --nolog -t $SAML2MODULEADD 1>>$saml2_log 2>&1
    $amadmin -i ${STAGING_DIR} -u amadmin -f "$FILE_ADMINPASSWD" --nolog -s ${servicexmls} 1>>$saml2_log 2>&1
 fi

 if [ $? -ne 0 ]; then
    displayMessage "Failed loading service"
    displayMessage ""
 fi
}

LoadSchema()
{
  SDS_INDEX="$BASEDIR/$PRODUCT_DIR/saml2/ldif/saml2_sds_index.ldif"
  SDS_SCHEMA="$BASEDIR/$PRODUCT_DIR/saml2/ldif/saml2_sds_schema.ldif"
  AD_SCHEMA="$BASEDIR/$PRODUCT_DIR/saml2/ldif/saml2_ad_schema.ldif"

  getKeyValue com.iplanet.am.directory.host
  DIR_HOST=$value
  getKeyValue com.iplanet.am.directory.port
  DIR_PORT=$value

  if [ "$SYSTEM" = "AM" ]; then
     LD_LIBRARY_PATH=$BASEDIR/$PRODUCT_DIR/ldaplib/ldapsdk:/usr/lib/mps:$LD_LIBRARY_PATH
     export LD_LIBRARY_PATH
     LDAPMODIFY="$BASEDIR/$PRODUCT_DIR/bin/ldapmodify"
     UMS_SCHEMA="$BASEDIR/$PRODUCT_DIR/saml2/config/xml/ums_addschema.xml"

     $LDAPMODIFY -h $DIR_HOST -p $DIR_PORT -D "$DS_DIRMGRDN" -a -j "$FILE_DS_DIRMGRPASSWD" -f $SDS_INDEX 1>>$saml2_log 2>&1
     $LDAPMODIFY -h $DIR_HOST -p $DIR_PORT -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -f $SDS_SCHEMA 1>>$saml2_log 2>&1

     $amadmin -u amadmin -f "$FILE_ADMINPASSWD" -c -t $UMS_SCHEMA 1>>$saml2_log 2>&1

     # update service table for AM
     cp -p $SvcTbl $SvcTbl.saml2
     AppendLine $SvcTbl \
		"iPlanetAMAuthService=Authentication" \
	        "sunAMAuthSAML2Service=Authentication"

  else
     line=`grep "^com.sun.identity.sm.sms_object_class_name=com.sun.identity.sm.ldap.SMSLdapObject" $amconfig`
     if [ "$line" != "" ]; then
         LDAPMODIFY="/usr/bin/ldapmodify"
         # Directory server/port in userdata
         line=`sed -n "
	    /userdefault/ {
	    n
	    p
         }" $serverconfigxml`
	
         eval `echo $line | awk -F' ' '{print $3}'`
         eval `echo $line | awk -F' ' '{print $4}'`
         host_userdefault=$host
         port_userdefault=$port

         line=`sed -n '
            /"default"/ {
            n
            p
         }' $serverconfigxml`
         eval `echo $line | awk -F' ' '{print $3}'`
         eval `echo $line | awk -F' ' '{print $4}'`

	 EDITFILES="$AD_SCHEMA"
	 tagSwap

         if [ -f $LDAPMODIFY ]; then
	    if [ "$host_userdefault" != "DIRECTORY_SERVER" ]; then
	         $LDAPMODIFY -h $host_userdefault -p $port_userdefault -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -f $AD_SCHEMA 1>>$saml2_log 2>&1
		 if [ "$?" != "0" ]; then
     			$LDAPMODIFY -h $host_userdefault -p $port_userdefault -D "$DS_DIRMGRDN" -a -j "$FILE_DS_DIRMGRPASSWD" -f $SDS_INDEX 1>>$saml2_log 2>&1
     			$LDAPMODIFY -h $host_userdefault -p $port_userdefault -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -f $SDS_SCHEMA 1>>$saml2_log 2>&1
		 else
		     displayMessage "ldif schema updated successfully!"
		 fi
            elif [ "$host" != "DIRECTORY_SERVER" ] && [ "$?" != "0" ]; then
	         $LDAPMODIFY -h $host -p $port -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -f $AD_SCHEMA 1>>$saml2_log 2>&1
		 if [ "$?" != "0" ]; then
     			$LDAPMODIFY -h $host -p $port -D "$DS_DIRMGRDN" -a -j "$FILE_DS_DIRMGRPASSWD" -f $SDS_INDEX 1>>$saml2_log 2>&1
     			$LDAPMODIFY -h $host -p $port -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -f $SDS_SCHEMA 1>>$saml2_log 2>&1
		 fi
	    fi
	 else
	    displayMessage "ldapmodify command not found. schema is not updated!!!"
         fi
     fi

  fi
}

DeleteServices() {
  services="sunFMSAML2MetadataService \
	    sunSAML2COTConfigService \
	    sunAMAuthSAML2Service"

  for s in $services
  do
     if [ "$SYSTEM" = "AM" ]; then
	$amadmin -u amadmin -f "$FILE_ADMINPASSWD" -r $s 1>>$saml2_log 2>&1
     else
	$amadmin -i ${STAGING_DIR} -u amadmin -f "$FILE_ADMINPASSWD" -r $s --nolog 1>>$saml2_log 2>&1
     fi
  done
}

DeleteSchema()
{
  if [ "$SYSTEM" = "AM" ]; then
     REMOVESAML2MODULE="$BASEDIR/$PRODUCT_DIR/saml2/config/xml/saml2_module_del.xml"
     $amadmin -u amadmin -f "$FILE_ADMINPASSWD" -t $REMOVESAML2MODULE 1>>$saml2_log 2>&1
  fi
}

CreateSaml2Meta()
{
 cp -p $amadmin $SAML2META
 InsertLine $SAML2META "AM_CLASSPATH=" "SAML2_CLASSPATH=$BASEDIR/$PRODUCT_DIR/saml2/locale:$BASEDIR/$PRODUCT_DIR/saml2/lib/saml2.jar"
 AppendLine $SAML2META "AM_CLASSPATH=" "AM_CLASSPATH=\$AM_CLASSPATH:\$SAML2_CLASSPATH"
 sed -e "s#com.iplanet.am.admin.cli.Main#com.sun.identity.saml2.meta.SAML2Meta#g" $SAML2META > /tmp/.saml2meta
 cp /tmp/.saml2meta $SAML2META

cat <<EONF >/tmp/amadmin.ver.$$
if [ "\$1" = "-V" ] || [ "\$1" = "-version" ]; then
   pdir=`dirname \$0`
   if [ -f \$pdir/version ]; then
      cat \$pdir/version
   else
      cat \$pdir/../lib/version
   fi
   exit 0
fi

EONF

 if [ "$SYSTEM" = "FM" ]; then
    sed -e 's#${PARAMS}#"$@"#g' $SAML2META > /tmp/.saml2meta
    cp /tmp/.saml2meta $SAML2META
cat <<EONF >/tmp/amadmin.usg.$$
USAGE:
        saml2meta -i <staging dir> import -u <userdn>
                  [-w <password>|-j <password file>] [-m <xml file name>]
                  [-x <xml file name>] [-t <circle of trust name>]
        saml2meta -i <staging dir> export -u <userdn>
                  [-w <password>|-j <password file>] -e <entity id> [-n]
                  [-m <xml file name>] [-x <xml file name>]
        saml2meta -i <staging dir> template -u <userdn>
                  [-w <password>|-j <password file>] [-e <entity id>]
                  [-s <metaAlias> [-a <certAlias>] [-f <certAlias>]]
                  [-d <metaAlias> [-b <certAlias>] [-g <certAlias>]]
                  -m <xml file name> -x <xml file name>
        saml2meta -i <staging dir> delete -u <userdn>
                  [-w <password>|-j <password file>] -e <entity id> [-c]
        saml2meta -i <staging dir> list -u <userdn>
                  [-w <password>|-j <password file>]       
        saml2meta -i <staging dir> cotcreate -u <userdn>
                  [-w <password>|-j <password file>]
                  -t <circle of trust name> [-p <prefix url>]
                  [-l <entity id, entity id,...>]
        saml2meta -i <staging dir> cotdelete -u <userdn>
                  [-w <password>|-j <password file>]
                  -t <circle of trust name>
        saml2meta -i <staging dir> cotadd -u <userdn>
                  [-w <password>|-j <password file>]
                  -t <circle of trust name> -e <entity id>
        saml2meta -i <staging dir> cotremove -u <userdn>
                  [-w <password>|-j <password file>]
                  -t <circle of trust name> -e <entity id>
        saml2meta -i <staging dir> cotmember -u <userdn>
                  [-w <password>|-j <password file>]
                  -t <circle of trust name>
        saml2meta -i <staging dir> cotlist -u <userdn>
                  [-w <password>|-j <password file>]              
        saml2meta -V
        saml2meta -?

DESCRIPTION:
        Manages SAML 2.0 metadata and extended configuration.

        The import subcommand is used to load standard metadata and/or extended
        configuration.
        The export is used to export standard metadata and/or extended
        configuration in XML format. At least one of '-m' or '-x' option is
        required.
        The template is used to generate standard metadata for a hosted entity.
        The delete is used to remove standard metadata and/or extended entity
        configuration.
        The list command is used to list all the entity id in the system.
        The cotcreate command is used to create the circle of trust.
        The cotdelete command is used to delete the circle of trust.
        The cotadd command is used to add trusted provider to the circle of
        trust.
        The cotremove command is used to remove trusted provider from the
        circle of trust.
        The cotmember command is used to list the trusted providers from the
        circle of trust.
        The cotlist command is used to list all the name of circle of 
        trust in the system.
OPTIONS:
        The following options are supported:
        -i <staging dir>
          The directory for the web application staging area created by fmwar
          command.  For example, /var/opt/SUNWam/fm/war_staging.

        -u <userdn>, --runasdn <userdn>
          Full DN of the user running the command

        -w <password>, --password <password>
          Specify password of the user running the command.

        -j <password file>, --passwordfile <password file>
          Specify file name containing password of the user running the
          command.

        -m <xml file name>, --metadata <xml file name>
          Specify file name for the standard metadata.

        -x <xml file name>, --extended <xml file name>
          Specify file name for the extended entity configuration.

        -e <entity id>, --entityid <entity id>
          Specify entity id.

        -s <metaAlias>, --serviceprovider <metaAlias>
          Specify metaAlias for hosted service provider to be created.
          The metaAlias must not contain "/".

        -a <certAlias>, --spcertalias <certAlias>
          Specify cert alias for hosted service provider to be created.

        -f <certAlias>, --specertalias <certAlias>
          Specify encryption cert alias for hosted service provider to be
          created.

        -d <metaAlias>, --identityprovider <metaAlias>
          Specify metaAlias for hosted identity provider to be created.
          The metaAlias must not contain "/".

        -b <certAlias>, --idpcertalias <certAlias>
          Specify cert alias for hosted identity provider to be created.

        -g <certAlias>, --idpecertalias <certAlias>
          Specify encryption cert alias for hosted identity provider to be
          created.

        -n, --sign
          Sign the exported xml file(s).

        -c, --extendedonly
          Delete extended entity configuration only.

        -t, --cot
          Name of the circle of trust
 
        -p, --prefix
          Prefix URL for idp discovery reader and writer url.
 
        -l, --trustedproviders
          List of trusted providers in the circle of trust.

        -V, --version
          Print version information.

        -?, --help
          Print help information (this message).
EOF
EONF
    ReplaceBlock $SAML2META "USAGE" "EOF" /tmp/amadmin.usg.$$
    rm /tmp/amadmin.usg.$$

    InsertBlock $SAML2META "# check dependent files exist" /tmp/amadmin.ver.$$
 else
    InsertBlock $SAML2META "# Setup proper LD_LIBRARY_PATH if not already set" /tmp/amadmin.ver.$$
 fi

 rm /tmp/amadmin.ver.$$

 grep com.sun.identity.saml2.meta.SAML2Meta $SAML2META | sed -e 's#"$@"#"$@" -w "$password"#g' > /tmp/.saml2meta
 echo "if [ \$? -eq 1 ]; then" >> $SAML2META
 echo "    oldmodes=\`stty -g\`" >> $SAML2META
 echo "    stty -echo" >> $SAML2META
 echo "    read password" >> $SAML2META
 echo "    stty \$oldmodes" >> $SAML2META
 echo "    echo ''" >> $SAML2META
 cat /tmp/.saml2meta >> $SAML2META
 echo "fi" >> $SAML2META

 rm /tmp/.saml2meta
}


ModifyAMC()
{
 echo "" >> $amconfig
 echo "# SAML2 properties" >> $amconfig
 echo "com.sun.identity.saml2.am_or_fm=$SYSTEM" >> $amconfig
 echo "com.sun.identity.saml2.xmlenc.EncProviderImpl=com.sun.identity.saml2.xmlenc.FMEncProvider" >> $amconfig
 echo "com.sun.identity.saml2.xmlenc.SigProviderImpl=com.sun.identity.saml2.xmlsig.FMSigProvider" >> $amconfig
 if [ "$SYSTEM" = "AM" ]; then
   echo "com.sun.identity.common.datastore.provider.default=com.sun.identity.saml2.plugins.IdRepoDataStoreProvider" >> $amconfig
 else
   echo "saml2=sunFMSAML2NameIdentifier" >> $amLDAPDataStoreProvider
 fi

}

RestoreAMC()
{
 DeleteLine $amconfig "# SAML2 properties"
 DeleteLine $amconfig "com.sun.identity.saml2.am_or_fm="
 DeleteLine $amconfig "com.sun.identity.saml2.xmlenc.EncProviderImpl="
 DeleteLine $amconfig "com.sun.identity.saml2.xmlenc.SigProviderImpl="
 if [ "$SYSTEM" = "AM" ]; then
   DeleteLine $amconfig "com.sun.identity.common.datastore.provider.default="
 else
   DeleteLine $amconfig "saml2=sunFMSAML2NameIdentifier"
 fi

}

displayToDoMessage()
{
if [ $INSTALL_OPTION = "install" -a $INSTALL_LEVEL = 1 ];then
    displayMessage "To complete the installation, please run saml2setup to configure AM/FM and redeploy the newly generated war file."

elif [ $INSTALL_OPTION = "configure" -o $INSTALL_LEVEL = 2 ];then
    displayMessage "To complete the installation of SAML2 you must deploy the war file. Refer to the web container documentation or the release notes for directions on deploying a war file."
else    # uninstall case
    displayMessage "Sun Java System SAML v2 plugin has been removed."
    displayMessage ""
    displayMessage "The war file was not undeployed from the web container. Refer to the web container documentation for directions on undeploying a war file."
fi

}

###############################################
# Replace block
###############################################
ReplaceBlock() {
  FILE=$1
  START_TAG=$2
  END_TAG=$3
  NEW_TEXT_FILE=$4

  $CP $FILE $FILE-tmp
  $NAWK 'BEGIN {
           IN_REPLACE = 0;
         };
         {
           if (index($0, START_TAG) > 0) {
            while (getline str < NEW_TEXT_FILE > 0) {
              if (length(str) > 0) {
                printf("%s\n", str);
              }
            }
             IN_REPLACE = 1;
           } else if (index($0, END_TAG) > 0) {
             if (IN_REPLACE == 0) {
               printf("%s\n", $0);
             }
             IN_REPLACE = 0;
           } else {
             if (IN_REPLACE == 0) {
               printf("%s\n", $0);
             }
           }
         };
         END {};' START_TAG="$START_TAG" END_TAG="$END_TAG" NEW_TEXT_FILE="$NEW_TEXT_FILE" $FILE-tmp > $FILE
  $RM -f $FILE-tmp
}

###############################################
# Insert before tag
###############################################
InsertBlock() {
  FILE=$1
  TAG=$2
  NEW_TEXT_FILE=$3

  $CP $FILE $FILE-tmp
  $NAWK 'BEGIN {};
         {
           if (index($0, TAG) > 0) {
             while (getline str < NEW_TEXT_FILE > 0) {
               if (length(str) > 0) {
                 printf("%s\n", str);
               }
             }
             printf("%s\n", $0);
           } else {
             printf("%s\n", $0);
           }
         };
         END {};' TAG="$TAG" NEW_TEXT_FILE="$NEW_TEXT_FILE" $FILE-tmp > $FILE
  $RM -f $FILE-tmp
}

InsertLine() {
  file="$1"
  match="$2"
  new="$3"

  sed -e "
/$match/ {
i\\
$new
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

DeleteLine() {
  file=$1
  match=$2

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

  sed -e "
/$match/ {
d
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

AppendLine() {
  file=$1
  match=$2
  new=$3

  sed -e "
/$match/ {
a\\
$new
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

ReplaceLine() {
  file=$1
  match=$2
  new=$3

  sed -e "
/$match/ {
c\\
$new
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

getKeyValue()
{
  value=`grep "^$1" $amconfig | sed -e "s#$1=##g"`
}

getSystemFiles()
{
    if [ "$SYSTEM" = "AM" ]; then
          
	if [ "$AM_INSTANCE" = "" ]; then
	    AMCONFIG="AMConfig.properties"
	    SERVERCONFIG="serverconfig.xml"
	    amadmin=$BASEDIR/$PRODUCT_DIR/bin/amadmin
	    SAML2META=$BASEDIR/$PRODUCT_DIR/saml2/bin/saml2meta
	else
	    AMCONFIG="AMConfig-$AM_INSTANCE.properties"
	    SERVERCONFIG="$AM_INSTANCE/serverconfig.xml"
	    amadmin=$BASEDIR/$PRODUCT_DIR/bin/amadmin.$AM_INSTANCE
	    SAML2META=$BASEDIR/$PRODUCT_DIR/saml2/bin/saml2meta.$AM_INSTANCE
	fi

	if [ "$OS" = "SunOS" ]; then
	    amconfig="/etc/opt/SUNWam/config/$AMCONFIG"
            serverconfigxml="/etc/opt/SUNWam/config/$SERVERCONFIG"
	else
	    amconfig="/etc/opt/sun/identity/config/$AMCONFIG"
	    serverconfigxml="/etc/opt/sun/identity/config/$SERVERCONFIG"
	fi

	webxml="$STAGING_DIR/WEB-INF/web.xml"
	sunwebxml="$STAGING_DIR/WEB-INF/sun-web.xml"
	iaswebxml="$STAGING_DIR/WEB-INF/ias-web.xml"
        SvcTbl="${STAGING_DIR}/WEB-INF/classes/amServiceTable.properties"

	locale_dir=$BASEDIR/$PRODUCT_DIR/locale
	AM_LOGGING=$BASEDIR/$PRODUCT_DIR/lib/am_logging.jar
	WAR_FILE_DIR=$BASEDIR/$PRODUCT_DIR
    else
	amconfig="$STAGING_DIR/web-src/WEB-INF/classes/AMConfig.properties"
	serverconfigxml="$STAGING_DIR/web-src/WEB-INF/config/serverconfig.xml"

	if [ "$OS" = "SunOS" ]; then
	    amadmin=$BASEDIR/SUNWam/fm/bin/amadmin
	else
	    amadmin=$BASEDIR/$PRODUCT_DIR/fm/bin/amadmin	    
	fi    
	webxml="$STAGING_DIR/web-src/WEB-INF/web.xml"
	sunwebxml="$STAGING_DIR/web-src/WEB-INF/sun-web.xml"
	iaswebxml="$STAGING_DIR/web-src/WEB-INF/ias-web.xml"
	locale_dir=$STAGING_DIR/web-src/WEB-INF/classes
	AM_LOGGING=$STAGING_DIR/web-src/WEB-INF/lib/am_logging.jar
	SAML2META=$BASEDIR/$PRODUCT_DIR/saml2/bin/saml2meta
	amLDAPDataStoreProvider="$STAGING_DIR/web-src/WEB-INF/classes/amLDAPDataStoreProvider.properties"
	WAR_FILE_DIR=$STAGING_DIR
    fi

    getKeyValue com.iplanet.am.server.host
    hostname="$value"
    getKeyValue com.iplanet.am.server.protocol
    protocol="$value"
    getKeyValue com.iplanet.am.server.port
    port="$value"
    getKeyValue com.iplanet.am.defaultOrg
    defaultOrg="$value"
    getKeyValue com.iplanet.am.jdk.path
    JAVA_HOME="$value"
    getKeyValue com.iplanet.am.services.deploymentDescriptor
    SERVER_DEPLOY_URI="$value"

    warfile=`echo ${SERVER_DEPLOY_URI} | sed -e "s#/*##"`".war"
    CURRENT_WAR_FILE="$WAR_FILE_DIR/$warfile"

    eval `grep encoding $serverconfigxml | awk -F' ' '{print $3}'`

    saml2_configured=`grep "# SAML2 properties" $amconfig`
}

BackupFiles()
{
    if [ "$saml2_configured" = "" ]; then
	if [ "$SYSTEM" = "AM" ]; then
	    if [ ! -f $CURRENT_WAR_FILE.saml2 ]; then
	        mv $CURRENT_WAR_FILE $CURRENT_WAR_FILE.saml2
	    fi
	    if [ ! -f $webxml.saml2 ]; then
	        cp -p $webxml $webxml.saml2
	    fi
	else
	    if [ ! -f $webxml.saml2 ]; then
	        cp -p $webxml $webxml.saml2
	    fi
            if [ -f $CURRENT_WAR_FILE ]; then
		if [ ! -f $CURRENT_WAR_FILE.saml2 ]; then
		    mv $CURRENT_WAR_FILE  $CURRENT_WAR_FILE.saml2
		fi
            fi
	    if [ ! -f $amLDAPDataStoreProvider.saml2 ]; then
		cp -p $amLDAPDataStoreProvider $amLDAPDataStoreProvider.saml2
	    fi
	fi
	cp -p $AM_LOGGING $AM_LOGGING.saml2
    fi
}

RestoreFiles()
{

    displayMessage "Restoring $SYSTEM configuration..."
    if [ "$saml2_configured" != "" ]; then
	RestoreAMC
	rm $SAML2META
	if [ "$SYSTEM" = "AM" ]; then
	    mv $CURRENT_WAR_FILE.saml2 $CURRENT_WAR_FILE
	    rm $STAGING_DIR/WEB-INF/lib/saml2.jar
            rm -rf $STAGING_DIR/saml2
	    mv $webxml.saml2 $webxml
	    rm $STAGING_DIR/config/auth/default/SAML2.xml
	    rm $STAGING_DIR/config/auth/default_en/SAML2.xml

	    if [ -d $STAGING_DIR/saml2 ]; then
		rm -rf $STAGING_DIR/saml2
	    fi

	    if [ -d $STAGING_DIR/samples/saml2 ]; then
		rm -rf $STAGING_DIR/samples/saml2
	    fi
	    if [ -f $SvcTbl.saml2 ]; then	
                mv $SvcTbl.saml2 $SvcTbl
	    fi
	else
	    mv $webxml.saml2 $webxml
            if [ -f $CURRENT_WAR_FILE.saml2 ]; then
		mv $CURRENT_WAR_FILE.saml2 $CURRENT_WAR_FILE
            fi
	    rm $STAGING_DIR/web-src/WEB-INF/lib/saml2.jar
	    rm $STAGING_DIR/web-src/config/auth/default/SAML2.xml
	    rm $STAGING_DIR/web-src/config/auth/default_en/SAML2.xml
	    mv $amLDAPDataStoreProvider.saml2 $amLDAPDataStoreProvider

	    if [ -d $STAGING_DIR/web-src/saml2 ]; then
		rm -rf $STAGING_DIR/web-src/saml2
	    fi

	    if [ -d $STAGING_DIR/web-src/samples/saml2 ]; then
		rm -rf $STAGING_DIR/web-src/samples/saml2
	    fi
	fi

	if [ -f $AM_LOGGING.saml2 ]; then
	    mv $AM_LOGGING.saml2 $AM_LOGGING
	fi

	rm -rf $BASEDIR/$PRODUCT_DIR/saml2/meta

	properties_files=`ls -1 $BASEDIR/$PRODUCT_DIR/saml2/locale`
	for f in $properties_files
	do
	    rm $locale_dir/$f
	done

	displayMessage ""

	displayMessage "Deleting SAML2 services ..."

        createPasswdFile

	DeleteServices

	if [ "$LOAD_SCHEMA" = "true" ]; then
	    displayMessage "Deleting SAML2 schema ..."
	    DeleteSchema
	fi

	removePasswdFile

	displayMessage ""
	displayMessage "SAML2 services deleted !!!"

    fi
}

copyJSP()
{
  if [ "$SYSTEM" = "FM" ]; then
	mkdir -p $STAGING_DIR/web-src/saml2/jsp
	if [ "$OS" = "SunOS" ]; then
	 cp $BASEDIR/SUNWam/saml2/config/jsp/* $STAGING_DIR/web-src/saml2/jsp
	else
         cp  $BASEDIR/$PRODUCT_DIR/saml2/config/jsp/* $STAGING_DIR/web-src/saml2/jsp
	 fi
  else
	mkdir -p $STAGING_DIR/saml2/jsp
	cp $BASEDIR/$PRODUCT_DIR/saml2/config/jsp/*  $STAGING_DIR/saml2/jsp
  fi
}

ModifyWebxml()
{

  web_xml=$BASEDIR/$PRODUCT_DIR/saml2/config/web.xml
  InsertBlock $webxml "<servlet-mapping>" $web_xml

  if [ "$SYSTEM" = "FM" ]; then
     mkdir -p $STAGING_DIR/web-src/saml2/jsp
     if [ "$OS" = "SunOS" ]; then
	 cp $BASEDIR/SUNWam/saml2/config/jsp/* $STAGING_DIR/web-src/saml2/jsp
     else
	 cp  $BASEDIR/$PRODUCT_DIR/saml2/config/jsp/* $STAGING_DIR/web-src/saml2/jsp
     fi
  else
     mkdir -p $STAGING_DIR/saml2/jsp
     cp $BASEDIR/$PRODUCT_DIR/saml2/config/jsp/*  $STAGING_DIR/saml2/jsp

     # comment out amlcontroller
     InsertLine $webxml "<filter>" "<!--"
     AppendLine $webxml "<\/filter-mapping>" "-->"

  fi
}

ModifyClasspath()
{
if [ "$SYSTEM" = "AM" ]; then
   cp $BASEDIR/$PRODUCT_DIR/saml2/lib/saml2.jar $STAGING_DIR/WEB-INF/lib
   if [ -f $BASEDIR/$PRODUCT_DIR/saml2/locale/fmSAML2Meta.properties.fm ]; then
      rm $BASEDIR/$PRODUCT_DIR/saml2/locale/fmSAML2Meta.properties.fm
   fi
   cp $BASEDIR/$PRODUCT_DIR/saml2/locale/* $BASEDIR/$PRODUCT_DIR/locale
   cp $BASEDIR/$PRODUCT_DIR/saml2/config/auth/SAML2.xml $STAGING_DIR/config/auth/default
   cp $BASEDIR/$PRODUCT_DIR/saml2/config/auth/SAML2.xml $STAGING_DIR/config/auth/default_en

   mkdir -p $BASEDIR/$PRODUCT_DIR/saml2/.tmp/com/sun/identity/log/messageid
   cp $BASEDIR/$PRODUCT_DIR/saml2/config/logging/SAML2LogMessageIDs.xml $BASEDIR/$PRODUCT_DIR/saml2/.tmp/com/sun/identity/log/messageid
   cd $BASEDIR/$PRODUCT_DIR/saml2/.tmp
   $JAVA_HOME/bin/jar uf $AM_LOGGING  com/sun/identity/log/messageid/SAML2LogMessageIDs.xml
   cd $CURR_DIR
   rm -rf $BASEDIR/$PRODUCT_DIR/saml2/.tmp

else
   if  [ -f $BASEDIR/$PRODUCT_DIR/saml2/locale/fmSAML2Meta.properties.fm ]; then
       mv $BASEDIR/$PRODUCT_DIR/saml2/locale/fmSAML2Meta.properties.fm $BASEDIR/$PRODUCT_DIR/saml2/locale/fmSAML2Meta.properties
   fi
   cp $BASEDIR/$PRODUCT_DIR/saml2/locale/*.properties $STAGING_DIR/web-src/WEB-INF/classes
   cp $BASEDIR/$PRODUCT_DIR/saml2/lib/saml2.jar $STAGING_DIR/web-src/WEB-INF/lib
   cp $BASEDIR/$PRODUCT_DIR/saml2/config/auth/SAML2.xml $STAGING_DIR/web-src/config/auth/default
   cp $BASEDIR/$PRODUCT_DIR/saml2/config/auth/SAML2.xml $STAGING_DIR/web-src/config/auth/default_en
fi
}

CreateMeta()
{
   displayMessage "Creating SAML2 IDP/SP Meta data ..."
   displayMessage " "

   mkdir -p $BASEDIR/$PRODUCT_DIR/saml2/meta
   cd $BASEDIR/$PRODUCT_DIR/saml2/meta
   if [ "$SYSTEM" = "AM" ]; then
      $SAML2META template -u amadmin -j "$FILE_ADMINPASSWD" -e $hostname -d idp -m idpMeta.xml -x idpExtended.xml
      $SAML2META template -u amadmin -j "$FILE_ADMINPASSWD" -e $hostname -s sp -m spMeta.xml -x spExtended.xml
   else
      $SAML2META -i ${STAGING_DIR} template -u amadmin -j "$FILE_ADMINPASSWD" -e $hostname -d idp -m idpMeta.xml -x idpExtended.xml
      $SAML2META -i ${STAGING_DIR} template -u amadmin -j "$FILE_ADMINPASSWD" -e $hostname -s sp -m spMeta.xml -x spExtended.xml
   fi
   displayMessage "Meta data created !!!"
   displayMessage " "

   if [ "$SYSTEM" = "AM" ]; then
      $SAML2META cotcreate -u amadmin -j "$FILE_ADMINPASSWD" -t samplecot
   else
      $SAML2META -i ${STAGING_DIR} cotcreate -u amadmin -j "$FILE_ADMINPASSWD" -t samplecot
   fi
}

configureIDPDiscovery()
{
   IDPDISCOVERY_WAR="$BASEDIR/$PRODUCT_DIR/saml2/idpdiscovery.war"
   mkdir -p $BASEDIR/$PRODUCT_DIR/saml2/.idpdiscovery
   cd $BASEDIR/$PRODUCT_DIR/saml2/.idpdiscovery
   $JAVA_HOME/bin/jar xf $IDPDISCOVERY_WAR
   EDIT_FILES="$BASEDIR/$PRODUCT_DIR/saml2/.idpdiscovery/WEB-INF/classes/IDPDiscoveryConfig.properties"
   tagSwap
   $JAVA_HOME/bin/jar uf $IDPDISCOVERY_WAR WEB-INF/classes/IDPDiscoveryConfig.properties
   cd $BASEDIR/$PRODUCT_DIR/saml2/
   rm -rf .idpdiscovery
   displayMessage ""
   displayMessage "IDP Discovery war file $IDPDISCOVERY_WAR is ready for deploy!"
}

installSamples()
{
  if [ "$SYSTEM" = "FM" ]; then
     mkdir -p $STAGING_DIR/web-src/samples/saml2/useCaseDemo
     if [ "$OS" = "SunOS" ]; then
         cp $BASEDIR/SUNWam/saml2/samples/useCaseDemo/* $STAGING_DIR/web-src/samples/saml2/useCaseDemo
     else
         cp $BASEDIR/$PRODUCT_DIR/saml2/samples/useCaseDemo/* $STAGING_DIR/web-src/samples/saml2/useCaseDemo
     fi
  else
     mkdir -p $STAGING_DIR/samples/saml2/useCaseDemo
     cp $BASEDIR/$PRODUCT_DIR/saml2/samples/useCaseDemo/*  $STAGING_DIR/samples/saml2/useCaseDemo
  fi
}

createPasswdFile()
{
   FILE_DS_DIRMGRPASSWD=/tmp/sun_is62_dsdirmgrpasswd
   touch $FILE_DS_DIRMGRPASSWD
   chmod 600 $FILE_DS_DIRMGRPASSWD
   $ECHO $DS_DIRMGRPASSWD > $FILE_DS_DIRMGRPASSWD
   export FILE_DS_DIRMGRPASSWD

   FILE_ADMINPASSWD=/tmp/sun_is62_adminpasswd
   touch $FILE_ADMINPASSWD
   chmod 600 $FILE_ADMINPASSWD
   $ECHO $ADMINPASSWD > $FILE_ADMINPASSWD
   export FILE_ADMINPASSWD

}

removePasswdFile()
{
   $RM $FILE_ADMINPASSWD
   $RM $FILE_DS_DIRMGRPASSWD
}

updateSAML2()
{

if [ "$saml2_configured" = "" ]; then
    displayMessage "SAML2 plugin have not been configured on the system yet!"
    displayMessage ""
    exit
fi

displayMessage "Update SAML2 plugin staging directory ..."

if [ "$DEPLOY_SAMPLES" = "true" ]; then
   displayMessage "Installing SAML2 samples ..."
   installSamples
fi

copyJSP

ModifyClasspath

CreateWarFile

}

configureSAML2()
{

createPasswdFile

if [ "$saml2_configured" != "" ]; then
    displayMessage "SAML2 plugin have been configured on the system already!"
    displayMessage ""
    exit
fi

displayMessage "Configuring SAML2 plugin ..."

BackupFiles

displayMessage ""

LoadServices

ModifyAMC

if [ ! -f $SAML2META ]; then
    CreateSaml2Meta
fi


ModifyWebxml

if [ "$DEPLOY_SAMPLES" = "true" ]; then
   displayMessage "Installing SAML2 samples ..."
   installSamples
fi

ModifyClasspath

CreateMeta

if [ "$LOAD_SCHEMA" = "true" ]; then
    displayMessage " "
    displayMessage "Loading SAML2 schema ..."
    LoadSchema
else
    displayMessage "SAML2 schema is not loaded into directory server"
fi

CreateWarFile

removePasswdFile

}
