<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:transform version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:query="http://www.novell.com/nxsl/java/com.novell.nds.dirxml.driver.XdsQueryProcessor">

   <!-- This insures that testing documents are well formed outside of DirXML -->
   <xsl:strip-space elements="*"/>
   <xsl:preserve-space elements="value component"/>
   <xsl:output indent="yes" method="xml"/>
   <xsl:param name="srcQueryProcessor"/>
   <xsl:param name="destQueryProcessor"/>

   <!-- identity transform for everything we don't want to mess with -->
   <xsl:template match="@*|node()">
      <xsl:copy>
         <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>        
   </xsl:template>

   <xsl:template match="add[@class-name='User']">
      <!--    Check for required fields    -->
      <xsl:if test="add-attr[@attr-name='Given Name'] and
                    add-attr[@attr-name='Surname'] and
                    add-attr[@attr-name='Full Name'] and
                    add-attr[@attr-name='Generational Qualifier']">
         <!--    Check for 'Generational Qualifier' value    -->
         <xsl:variable name="GenQualValue" select="add-attr[@attr-name='Generational Qualifier']/value"/>
         <xsl:if test="$GenQualValue = 'P' or $GenQualValue = 'p'">
            <!--    sends 'src-dn' and receives the user's context in 'context-name' variable   -->
            <xsl:variable name="context-name">
               <xsl:call-template name="get-dn-prefix">
                  <xsl:with-param name="src-dn" select="@src-dn"/>
               </xsl:call-template>
            </xsl:variable>
            <!-- copy the add through -->
            <xsl:copy>
               <xsl:apply-templates select="@*|node()"/>
               <add-attr attr-name="CorpTreePosition">
                  <value><xsl:value-of select="$context-name"/></value>
               </add-attr>
            </xsl:copy>
         </xsl:if>
         <!--  if the if fails, means 'Generational Qualifier' <> 'p' or 'P'  -->
      </xsl:if>
      <!--  if the if fails, means we don't have all the required attributes  -->
   </xsl:template>

   <!--  This templates receives '\TREE\O\...\OU\CN' and returns '\O\...\OU'  -->
   <xsl:template name="get-dn-prefix" xmlns:jstring="http://www.novell.com/nxsl/java/java.lang.String">
      <xsl:param name="src-dn"/>
      <xsl:variable name="dn" select="jstring:new($src-dn)"/>
      <xsl:variable name="second_slash" select="jstring:IndexOf($dn,'\',1)"/>
      <xsl:variable name="final_slash" select="jstring:lastIndexOf($dn,'\')"/>
      <xsl:if test="$second_slash != -1">
         <!--  returns the string without \TREE and without \CN   -->
         <xsl:value-of select="jstring:substring($dn,$second_slash,$final_slash)"/>
      </xsl:if>
   </xsl:template>
</xsl:transform>

