#!/bin/sh
#* ----------------------------------------------------------------------
#*               Proprietary and Confidential Information
#*
#* This material contains, and is part of a computer software program
#* which is, proprietary and confidential information owned by COMPUTER
#* ASSOCIATES INTERNATIONAL, INC.  The program, including this material,
#* may not be duplicated, disclosed or reproduced in whole or in part for
#* any purpose without the express written authorization of COMPUTER
#* ASSOCIATES. All authorized reproductions must be marked with this
#* legend.
#*
#*                          Copyright (c) 1992-2007
#*             Computer Associates International, Incorporated
#*                          All rights reserved
#*
#* ----------------------------------------------------------------------
#*  SCCS Module Control Stamp
#* ----------------------------------------------------------------------
#
#* "@(#)caprofile	1.33  01/19/07 10:06:00"
#* "Copyright (C) 1992-2007 Computer Associates International, Inc.  All rights reserved."
#

[ "$DEBUG_CAPROFILE" != "" ] && set -x

Comments()
{
cat - << EOF

NAME
	caprofile - Utility to set environment variables and update system profiles.
	

SYNOPSIS

 caprofile  [options] [variable] <variable-value> <[bash_script csh_script] [-section section_name]>

 a) caprofile -s [variable]

 b) caprofile -s [variable] <variable-value>

 c) caprofile -s [variable] <[ bash_script  csh_script ]>

 d) caprofile -s [variable] <[ <variable-value> [  bash_script  csh_script ]]> 

 e) caprofile -q [variable]

 f) caprofile -d [variable1 <variable2> ... <variableN>]

 g) caprofile -d <variable1 variable2 ... variableN> -section [section1 <... sectionN>]

 h) caprofile -F

 i) caprofile [<-h> | <-?>]

 Note: [] means they are mandatory
       <> means they are optional.

DESCRIPTION
	caprofile is a Unix/Linux utility to update/query/delete environment variables from 
	/etc/profile.CA and /etc/csh.login.CA (henceforth referred to as profile_CA).

	- caprofile is intended only for "root" user. Script will exit with 
		return code of 5 if a non-root user tries to execute it.
	
	- By default, this caprofile script will execute $CASHCOMP/csutils/bin/caprofile 
		if it exists. This is to prevent products embedding an outdated version of 
		caprofile to have an adverse affect on the setting of variables in profile_CA.
		To override this behavior and to always use the behavior in the current script,
		set CAPROFILE_OVERRIDE=1 in your environment prior to this script execution.

	- Set/reset any variable using caprofile from $CASHCOMP/csutils/bin/
		(e.g. caprofile -s ANYVAR varvalue) to fix profile_CA problems which were 
		created by products embedding an outdated version of caprofile.
OPTIONS
  -s	Updates environment variable in profile_CA. It also
		sources profile_CA into /etc/profile (for Bourne shell) and 
		/etc/csh.login (/etc/.login, etc..) scripts for C-shell if 
		Update_Profile environment variable is set to 1.
		
	
		  i) [variable]
				Updates the variable based on the environment at
				the time of invoking this utility.

		 ii) [variable] <variable-value>	
				Updates the variable based on the value passed.

		iii) [variable] <[ bash_script  csh_script ]>
				Updates the variable based on the environment at
				the time of invoking this utility. Additionally 
				you can attach bash script and a c-shell specific
				scripts to set additional variables in the
				environment based on the script. 
				These scripts should be relative to the path of the
				variable-value.
    
		 iv) [variable] <[ <variable-value> [  bash_script  csh_script ]]>
				Updates the variable based on the value passed.
				Additionally you can attach bash script and a c-shell 
				specific scripts to set additional variables in the
				environment based on the script.


  -section
        This option should be used in conjunction with '-s' option.
        This is useful to set variables in a private section in profile_CA.

        Syntax is similar to '-s' with additional '-section section_name'
        arguments.

        Same variable could be set in multiple sections. But, same variable
        cannot be set as a global/public variable and as a private (section)
        variable.

        Variables within the sections will ONLY be set in the environment
        if CA_SECTION=<section-name> variable is set before sourcing
        profile_CA. On Linux (only) systems an argument could be passed
        while sourcing profile_CA to get the same sections functionality.
        However, CA_SECTION variable will take precedence over the argument 
        if it is set.

        Global/public variables (default) will always be set while sourcing 
        profile_CA with or without CA_SECTION variable.

        To set a section within profile_CA:
        -----------------------------------

        caprofile -s  II_SYSTEM  \$II_SYSTEM  ingres/.ingEIbash  ingres/.ingEIcsh  -section ccs
        caprofile -s  II_SYSTEM  \$II_SYSTEM  -section brightstor
        caprofile -s  II_SYSTEM  -section etrust
        caprofile -s  CASHCOMP   \$CASHCOMP  scripts/bash-cashcomp scripts/csh-cashcomp

        Sourcing profile_CA to get the variables set in the environment:
        ----------------------------------------------------------------

        To set variables within multiple sections, CA_SECTION could be set
        to the following values:

        all -> Source all the variables including variables in all the sections.
				CA_SECTION=all; . /etc/profile.CA

        <section_name> -> Source the variables in the section specified by the
                    <section_name> including all the public variables.
				CA_SECTION=<section-name>; . /etc/profile.CA

        minimum -> Set $CASHCOMP only (along with scripts attached during setting of

                    CASHCOMP [i.e. source environment of scripts/bash-cashcomp as shown above]
                     (minimum section is automatically set during setting of CASHCOMP).
				CA_SECTION=minimum; . /etc/profile.CA

        Syntax of sourcing profile_CA
        -----------------------------

        a) '. /etc/profile.CA' or 'source /etc/csh_login.CA'

        b) 'CA_SECTION=<section-name>; . /etc/profile.CA' or 
           'setenv CA_SECTION <section-name>;source /etc/csh_login.CA'

        c) 'CA_SECTION=all;. /etc/profile.CA' or 
            'setenv CA_SECTION all;source /etc/csh_login.CA'

        d) 'CA_SECTION=minimum;. /etc/profile.CA' or 
           'source /etc/csh_login.CA minimum'
		
        e) (Linux Only)
           '. /etc/profile.CA <section-name>' or
           'source /etc/csh_login.CA <section-name>'

  -q	Query and validate the variable's value from the environment and
		from profile_CA. Outputs the value if set and valid then sets the
		the return code to zero, otherwise exits with a non-zero return code.
  

  -d	Delete the variable(s) or sections from profile_CA

        Syntax: caprofile -d VAR1 VAR2 VAR3	
        Above syntax deletes VAR1, VAR2, and VAR3 variables from profile_CA

        Syntax: caprofile -d <variable1 variable2 ... variableN> -section [section1 <... sectionN>]	
        Above syntax deletes the variables variable1, variable2, 
        variableN from the sections section1, sectionN

        While deleting variables only '-section' and section arguments could be eliminated
		While deleting entire sections variable1, variableN arguments could be eliminated.

  -F    Fix start and end sections of profile_CA if they are incorrect.
	
  -h	Help (this screen).

  -?	Help (this screen).


RETURN CODE

	Zero if succesful otherwise non-zero.
		
		
EXAMPLES

# caprofile -s CASHCOMP
# caprofile -s CASHCOMP /opt/CA/SharedComponents
# caprofile -s CALIB  \$CASHCOMP/lib ../bin/envusr ../bin/envusrcsh
# caprofile -s CAIGLBL0000 scripts/envusr scripts/envusrcsh
# caprofile -s AGENT_DIR \$AGENT_DIR -section CCS
# caprofile -s AGENT_DIR /extra/agents scripts/envusr scripts/envusrcsh -section NSM

# caprofile -q CASHCOMP
# caprofile -?
# caprofile -d CABIN CALIB AGENT_DIR
# caprofile -d AGENT_DIR -section NSM

EOF

}

# chek the return code.. if not zero exit.
check_rc()
{
        if [ "$?" != "0" ];then
			restoreOriginalPermissions
			rm_tmpfiles
			exit 8
        fi
}

#+----------------------------------------------------------------------------+
#| Input Paramters:                                                           |
#|         perms: This is the permission string from ls -l for permpos        |
#|       permpos: This specifies position of perms (u=user, g=group, o=others |
#|                                                                            |
#|     Called From: getPerms                                                  |
#+----------------------------------------------------------------------------+
getPermSet()
{
	perms=$1
	permpos=$2

	rVal=0
	wVal=0
	xVal=0
	sVal=0

	case "$permpos" in
		"u")
			rVal=400
			wVal=200
			xVal=100
			sVal=4000 ;;
		"g")
			rVal=40
			wVal=20
			xVal=10
			sVal=2000 ;;
		"o")
			rVal=4
			wVal=2
			xVal=1
			sVal=1000 ;;
	esac

	p=`echo $perms | cut -c1`
	savR=0
	if [ "$p" = "r" ]; then 
		savR=${rVal}
	fi

	p=`echo $perms | cut -c2`
	savW=0
	if [ "$p" = "w" ]; then 
		savW=${wVal}
	fi

	p=`echo $perms | cut -c3`
	savX=0
	if [ "$p" = "x" ]; then 
		savX=${xVal}
	fi
	if [ "$p" = "S" -o "$p" = "T" -o "$p" = "l" ]; then
		savX=$sVal
	fi
	if [ "$p" = "s" -o "$p" = "t" ]; then
		savX=`expr ${xVal} + ${sVal}`
	fi

	octalPerm=`expr ${savR} + ${savW} + ${savX}`
}

#+----------------------------------------------------------------------------+
#| Input Paramters:                                                           |
#|    targetFile: The file to determine the current octal permissions for     |
#|                octal permissions maintained in octalPerms                  |
#|                                                                            |
#|     Called From:                                                           |
#+----------------------------------------------------------------------------+
getPerms()
{
	targetFile=$1

	# Get user permissions from ls -l output string
	perms=`ls -l ${targetFile} | cut -c2-4`
	getPermSet "$perms" "u"
	uPerms=$octalPerm

	# Get group permissions from ls -l output string
	perms=`ls -l ${targetFile} | cut -c5-7`
	getPermSet "$perms" "g"
	gPerms=$octalPerm

	# Get others permissions from ls -l output string
	perms=`ls -l ${targetFile} | cut -c8-10`
	getPermSet "$perms" "o"
	oPerms=$octalPerm

	# Combine all permissions in octal format in octalPerms
	octalPerms=`expr ${uPerms} + ${gPerms} + ${oPerms}`
}

#+----------------------------------------------------------------------------+
#| Input Paramters:                                                           |
#|    targetFile: The file to restore the saved octal permissions to          |
#|                octal permissions restored from octalPerms                  |
#|                                                                            |
#|     Called From:                                                           |
#+----------------------------------------------------------------------------+
restorePermissions()
{
	targetFile="$1"
	restorePerms="$2"
	[ "${restorePerms}" = "" ] && return 0

	chmod ${restorePerms} "${targetFile}" > /dev/null 2>&1
}

#+----------------------------------------------------------------------------+
#| Input Paramters:                                                           |
#|    None                                                                    |
#|                                                                            |
#|     Called From: MAINLINE                                                  |
#+----------------------------------------------------------------------------+
getCurrentPermissions()
{
	if [ -f "/etc/profile" ]; then
		getPerms "/etc/profile"
		etcProfilePerms=$octalPerms
	fi
	if [ -f "${HOME}/.profile" ]; then
		getPerms "${HOME}/.profile"
		homeProfilePerms=$octalPerms
	fi
	if [ -f "/etc/cshrc" ]; then
		getPerms "/etc/cshrc"
		etcCshrcPerms=$octalPerms
	fi
	if [ -f "/etc/.login" ]; then
		getPerms "/etc/.login"
		etcLoginPerms=$octalPerms
	fi
	if [ -f "/etc/login.csh" ]; then
		getPerms "/etc/login.csh"
		etcLogincshPerms=$octalPerms
	fi
	if [ -f "/etc/csh.login" ]; then
		getPerms "/etc/csh.login"
		etcCshloginPerms=$octalPerms
	fi
}

#+----------------------------------------------------------------------------+
#| Input Paramters:                                                           |
#|    None                                                                    |
#|                                                                            |
#|     Called From: MAINLINE                                                  |
#+----------------------------------------------------------------------------+
restoreOriginalPermissions()
{
	if [ -f "/etc/profile" -a "${etcProfilePerms}" != "" ]; then
		restorePermissions "/etc/profile" "${etcProfilePerms}"
	fi
	if [ -f "${HOME}/.profile" -a "${homeProfilePerms}" != "" ]; then
		restorePermissions "${HOME}/.profile" "${homeProfilePerms}"
	fi
	if [ -f "/etc/cshrc" -a "${etcCshrcPerms}" != "" ]; then
		restorePermissions "/etc/cshrc" "${etcCshrcPerms}"
	fi
	if [ -f "/etc/.login" -a "${etcLoginPerms}" ]; then
		restorePermissions "/etc/.login" "${etcLoginPerms}"
	fi
	if [ -f "/etc/login.csh" -a "${etcLogincshPerms}" != "" ]; then
		restorePermissions "/etc/login.csh" "${etcLogincshPerms}"
	fi
	if [ -f "/etc/csh.login" -a "${etcCshloginPerms}" != "" ]; then
		restorePermissions "/etc/csh.login" "${etcCshloginPerms}"
	fi
}

#+----------------------------------------------------------------------------+
#| Input Paramters:                                                           |
#|         upd_var: This is the install directory to update (CAIGLBL0000)     |
#|   upd_file_name: The login profile to update (/etc/profile)                |
#|                                                                            |
#|     Called From: upd_env_variable                                          |
#+----------------------------------------------------------------------------+
rm_ca_var_update()
{
  upd_var="$1"
  upd_file_name="$2"
  linecount=0
  firstline=0
  lastline=0

  rm -f /tmp/profile1.$PID 2>/dev/null

  grep -n "$upd_var" "$upd_file_name" |cut -d ':' -f1 >/tmp/cai_mod.$PID 2>/dev/null

	case "$upd_var" in 

	"JI_SYSTEM" | "AGENTWORKS_DIR" | "II_SYSTEM" | "CAIGLBL0000" )

		if [ -s /tmp/cai_mod.$PID ];then
			for lineno in `cat /tmp/cai_mod.$PID`
			do
				linecount=`expr $linecount + 1`

				if [ "$linecount" -eq 1 ];then
				  firstline="$lineno"
				fi

				lastline=$lineno
			done

		 if [ "$firstline" -ne 0 -a "$lastline" -ne 0 ];then 
			startline=`expr $firstline - 3`
			endline=`expr $lastline + 4`

		  if [ "$firstline" -ne "$lastline" ];then

			sed -e  "$startline,"$endline"d" "$upd_file_name" >/tmp/profile1.$PID 2>/dev/null
			if [ "$?" -eq 0 -a -s /tmp/profile1.$PID ];then
			 cat /tmp/profile1.$PID > "$upd_file_name"
			fi
		  fi


			if [ "$upd_file_name" = "/etc/cshrc" -o "$upd_file_name" = "/etc/.login" \
				-o "$upd_file_name" = "/etc/login.csh" -o "$upd_file_name" = "/etc/csh.login" ];then

				# only do the following for C-shell login scripts
				sed -e "/setenv $upd_var /d" "$upd_file_name" >/tmp/profile1.$PID 2>/dev/null

				if [ "$?" -eq 0 -a -s /tmp/profile1.$PID ];then
				 mv -f /tmp/profile1.$PID "$upd_file_name"
				fi

				firstl=""

				if [ "$upd_var" = "AGENTWORKS_DIR" ];then

					firstl=`grep -n "if ( -f .*\/atech\/scripts\/envusrcsh" "$upd_file_name" |grep -v "\#[ \t]*if" | cut -d ':' -f1`

				elif [ "$upd_var" = "JI_SYSTEM" ];then

					firstl=`grep -n "if ( -f .*\/jasmine\/framework\/files\/jasiienv.cshrc" "$upd_file_name" |grep -v "\#[ \t]*if" | cut -d ':' -f1`

				elif [ "$upd_var" = "CAIGLBL0000" ];then
				
					sed -e "/setenv CA_DB /d" "$upd_file_name" >/tmp/profile1.$PID 2>/dev/null
					if [ "$?" -eq 0 -a -s /tmp/profile1.$PID ];then
						mv -f /tmp/profile1.$PID "$upd_file_name"
					fi
					
					envcsh_line=`grep -n "source $CAIGLBL0000\/scripts\/envusrcsh" "$upd_file_name" 2>/dev/null|cut -d":" -f1`
					if [ "$envcsh_line" = "" ];then
						if [ -h "$CAIGLBL0000" -a -d "$CAIGLBL0000" ];then
								
							real_dir=`ls -l "$CAIGLBL0000" | $AWK -F' -> ' '{print $2}'`
							envcsh_line=`grep -n "source $real_dir\/scripts\/envusrcsh" "$upd_file_name" 2>/dev/null|cut -d":" -f1`
						fi

					fi
					
					if [ "$envcsh_line" != "" ];then
						for _csh_line in $envcsh_line
						do
								sed -e "${_csh_line}"d "$upd_file_name" >/tmp/profile1.$PID 2>/dev/null
								if [ "$?" -eq 0 -a -s /tmp/profile1.$PID ];then
									mv -f /tmp/profile1.$PID "$upd_file_name"
								fi
						done
					fi
		
	
				fi

					if [ "$firstl" != "" ];then
					for line11 in $firstl
					do
							_fline=$line11
							lastl=`expr $_fline + 2`
							sed -e "${_fline},${lastl}d" "$upd_file_name" >/tmp/profile2.$PID
							if [ "$?" -eq 0 -a -s /tmp/profile2.$PID ];then
								mv -f /tmp/profile2.$PID "$upd_file_name"
							fi
							rm -f /tmp/profile2.$PID
							
						break
					done
					fi
			fi # if [ "$upd_file_name" = "/etc/cshrc" -o "$upd_file_name" = "/etc/.login"
			
			# now remove comments!
			if [ "$upd_var" = "JI_SYSTEM" ];then
			 sed -e "/^\#.* Jasmine/d" "$upd_file_name" >/tmp/profile1.$PID 2>/dev/null
			 if [ "$?" -eq 0 -a -s /tmp/profile1.$PID ];then
				cat /tmp/profile1.$PID > "$upd_file_name"
			 fi
			elif [ "$upd_var" = "AGENTWORKS_DIR" ];then
			 sed -e "/^\#.* Agent Technology/d" "$upd_file_name" >/tmp/profile1.$PID 2>/dev/null
			 if [ "$?" -eq 0 -a -s /tmp/profile1.$PID ];then
				cat /tmp/profile1.$PID > "$upd_file_name"
			 fi

			 sed -e "/^\#.*odifications made by Unicenter NSM/d" "$upd_file_name" >/tmp/profile1.$PID 2>/dev/null
			 if [ "$?" -eq 0 -a -s /tmp/profile1.$PID ];then
				cat /tmp/profile1.$PID > "$upd_file_name"
			 fi
			elif [ "$upd_var" = "II_SYSTEM" ];then
			 sed -e "/^\#.* Ingres/d" "$upd_file_name" >/tmp/profile1.$PID 2>/dev/null
			 if [ "$?" -eq 0 -a -s /tmp/profile1.$PID ];then
				cat /tmp/profile1.$PID > "$upd_file_name"
			 fi
			elif [ "$upd_var" = "CAIGLBL0000" ];then
			 sed -e "/^\#.*Unicenter NSM install/d" "$upd_file_name" >/tmp/profile1.$PID 2>/dev/null
			 if [ "$?" -eq 0 -a -s /tmp/profile1.$PID ];then
				cat /tmp/profile1.$PID > "$upd_file_name"
			 fi
			fi # end if-else JI_SYSTEM

			
       fi # firstline -ne 0 -a lastline -ne 0

	  fi ;; #end if -s /tmp/cai_mod.$PID

	esac

   rm -f /tmp/cai_mod.$PID /tmp/profile1.$PID 2>/dev/null
}

#+----------------------------------------------------------------------------+
#| Input Paramters:                                                           |
#|         upd_var: This is the install directory to update (CAIGLBL0000)     |
#|   upd_file_name: The login profile to update (/etc/csh.login, /etc/profile)|
#|                                                                            |
#|     Called From: set_to_update_profile_csh_CA                              |
#| Desc: Used to delete the variables from profile.CA
#+----------------------------------------------------------------------------+

del_ifln()
{
	lineno=0
	file2del="$1"
	file="$file2del"
	[ "$file2del" = "" ] && { restoreOriginalPermissions; exit 6; }

	upd_var="$2"

	actfiln=0

	same_section=""
	another_section_found=""

	rm -f /tmp/mod_file2del.$PID /tmp/var_ifln_file.$PID /tmp/filn_file.$PID 2>/dev/null

	if [ -s "$file2del" ];then

		if [ "${section_variable}" != "" ];then

			if [ "$upd_var" = "" ];then

				grep -n "if[ \t]*\[.* -o \"\$CA_SECTION\" = \"${section_variable}\" \\\) -a " "$file2del" |grep -v "\#[ \t]*if" | cut -d ':' -f1 >/tmp/var_ifln_file.$PID

			else

				grep -n "if[ \t]*\[.* -o \"\$CA_SECTION\" = \"${section_variable}\" \\\) -a ${upd_var} " "$file2del" |grep -v "\#[ \t]*if" | cut -d ':' -f1 >/tmp/var_ifln_file.$PID

			fi

			[ -s "/tmp/var_ifln_file.${PID}" ] && same_section="1"

		fi

		  if [ "$upd_var" != "" ];then
		    if [ ! -s "/tmp/var_ifln_file.$PID" ];then 
				grep -n "if[ \t]*\[.* -a ${upd_var}[ \t]*\]" "$file2del" |grep -v "\#[ \t]*if" | cut -d ':' -f1 >/tmp/var_ifln_file.$PID

				if [ -s "/tmp/var_ifln_file.${PID}" -a "$delarg" != "1" ];then
					[ "$section_variable" != "" ] && return 0
					another_section_found="1"

				fi
		    fi

			if [ ! -s "/tmp/var_ifln_file.${PID}" ];then
			   grep -n "if[ \t]*\[.*\$"${upd_var}"" "$file2del" |\
				grep -v "\$"${upd_var}"[a-zA-Z0-9_-]" |\
				grep -v "\#[ \t]*if" | cut -d ':' -f1 >/tmp/var_ifln_file.$PID

			   [ -s "/tmp/var_ifln_file.${PID}" ] && reg_if_section="1"
			
			fi

		  fi # "$upd_var" != ""
		
		[ ! -s /tmp/var_ifln_file.$PID ] && return 0

		if [ -s /tmp/var_ifln_file.$PID ];then
			
			no_lines_del=0

			for var_ifln in `cat /tmp/var_ifln_file.$PID`
			do	
			
				[ "$actfiln" -gt "$var_ifln" ] && continue

				file2del="$1"
				[ "$no_lines_del" -gt 0 ] && \
					var_ifln=`expr $var_ifln - $no_lines_del`

				[ "$var_ifln" = "" ] && return

				line_del=`expr $var_ifln - 1`

				if [ "$line_del" != "" -a "$line_del" -gt 0 ] ;then
					sed -e "1,"$line_del"d" "$file2del" > /tmp/mod_file2del.$PID
					check_rc
				elif [ "$var_ifln" = "1" ];then
					cat "$file2del" > /tmp/mod_file2del.$PID
					check_rc
				fi

				file2del="/tmp/mod_file2del.$PID"

				[ ! -s /tmp/mod_file2del.$PID ] && return
				
				grep -n "fi" "$file2del" |grep -v "[a-zA-Z0-9_-]fi" |\
					grep -v "fi[a-zA-Z0-9_-]" |\
					grep -v "\#[ \t]*fi" |\
					cut -d ':' -f1 >/tmp/filn_file.$PID

				check_rc


				[ ! -s /tmp/filn_file.$PID ] && return

				grep -n "if[ \t]*\[" "$file2del" |\
					grep -v "\#[ \t]*if" | cut -d ':' -f1 >/tmp/ifln_file.$PID

				check_rc

				[ ! -s /tmp/ifln_file.$PID ] && return

				iffcnt=0	

				for filn in `cat /tmp/filn_file.$PID`
				do
					[ "$filn" = "" ] && return

					filn_sav="$filn"



				  if [ "$iffcnt" = "0" ];then


					for ifln in `cat /tmp/ifln_file.$PID`	
					do
						[ "$filn" = "" ] && return

						[ "$ifln_sav" = "" ] && ifln_sav="$ifln"
						
						if [ "$filn" -gt "$ifln" ];then

							iffcnt=`expr $iffcnt + 1`

						else

							break

						fi # end if "$filn" -gt "$ifln"

					done #end for ifln
				  fi # end if "$iffcnt" = "0"

				  if [ "$iffcnt" -gt 1 ]; then
						iffcnt=`expr $iffcnt - 1`
						continue
				  fi

				  if [ "$iffcnt" -gt 0 ]; then

						if [ "$line_del" != "" -a "$line_del" -gt 0 ];then
							actfiln=`expr $filn_sav + $lineno + $line_del`
							actifln=`expr $var_ifln + $lineno`
						else
							actfiln=`expr $filn_sav + $lineno`
							actifln=`expr $var_ifln + $lineno`
						fi


						if [ "$actfiln" -ge "$actifln" ];then

							sed -e "${actifln},${actfiln}d" "$file" > /tmp/profile_final.$PID
							check_rc

							no_lines_del=`expr ${no_lines_del} + ${actfiln} - ${actifln} + 1`

							mv -f /tmp/profile_final.$PID "$file"


						fi	

						iffcnt=0
						break
				  fi # end if "$iffcnt" -gt 0 


				done #end for filn

			done #end for var_ifln

	  fi # end if [ -s /tmp/var_ifln_file.$PID ]

	fi #end if $? -eq 0 -a -s "$file2del"

	#Remove temporary files
	rm -f /tmp/mod_file2del.$PID /tmp/var_ifln_file.$PID /tmp/filn_file.$PID /tmp/ifln_file.$PID 2>/dev/null

}

del_var_bash()
{

	reg_section=0

	d_VAR="$1"
	[ "$d_VAR" = "" ] && { restoreOriginalPermissions; exit 6; }

	file="$2"
	[ ! -f "$file" ] && { restoreOriginalPermissions; exit 7; }

	if [ "$file" = /etc/profile -o "$file" = "$HOME/.profile" ];then

	   case "$d_VAR" in

		   "JAVA_HOME" | "CATALINA_HOME" | "AXIS_HOME" ) return 90

	   esac
	fi

	# velsu01
	# remove 'minimum' section

	sed -e "/\[ \"\$CA_SECTION\" = \"minimum\" -a $d_VAR \] && return 0/d" "$file" >/tmp/profile_found.$PID 2>/dev/null

	[ "$?" = "0" ] && mv -f /tmp/profile_found.$PID "$file"

	rm -f /tmp/profile_found.$PID 2>/dev/null
        #velsu01

	lineno=0
	del_ifln "$file" "$env_var"

	[ "$same_section" != "1" -a "$another_section_found" != "1" -a "$reg_if_section" != "1" ] && reg_section=1

	[ "$reg_section" != "1" ] && \
		[ "$delarg" != "1" ] && [ "$reg_if_section" != "1" -o "$another_section_found" = "1" ] && return 0


	if [ "$same_section" != "1" ];then
		rm -f /tmp/var_ifln_file.$PID 2>/dev/null

		grep -n "if[ \t]*\[.* -a ${upd_var}[ \t]*\]" "$file" |grep -v "\#[ \t]*if" | cut -d ':' -f1 >/tmp/var_ifln_file.$PID 2>/dev/null

		[ -s "/tmp/var_ifln_file.${PID}" ] && another_section_found="1"

		rm -f /tmp/var_ifln_file.$PID 2>/dev/null
	fi
		

	[ "$same_section" = "1" -o "$another_section_found" = "1" ] && return 0

	grep -n "${d_VAR}=" "$file" |\
	  grep -v "[a-zA-Z0-9_-]+${d_VAR}=" |\
	  grep -v "\#[ \t]*${d_VAR}" |cut -d ':' -f1 >/tmp/cai_mod.$PID

	if [ -s /tmp/cai_mod.$PID ];then

		sort -nr /tmp/cai_mod.$PID -o /tmp/cai_mod.$PID

		for lineno in `cat /tmp/cai_mod.$PID`
		do
			# delete one line where the variable is set
			sed -e "${lineno}d" "$file" > /tmp/profile_found.$PID
			check_rc

			mv -f /tmp/profile_found.$PID "$file"

		done # end for lineno in
	fi # end if -s /tmp/cai_mod.$PID

	sed -e "/export ${d_VAR}[ \t]*$/d" "$file" > /tmp/profile_final.$PID
	check_rc

	mv -f /tmp/profile_final.$PID "$file"

	grep -n "export ${d_VAR}" "$file" |\
		grep -v "export ${d_VAR}[a-zA-Z0-9_-]" |egrep -v "${d_VAR}[ \t]+[a-zA-Z0-9_-]" |\
		cut -d ":" -f1 > /tmp/cai_mod.$PID 2>/dev/null

	if [ "$?" = "0" -a -s /tmp/cai_mod.$PID ];then

		sort -nr /tmp/cai_mod.$PID -o /tmp/cai_mod.$PID

		for lineno in `cat /tmp/cai_mod.$PID`
		do
			sed -e "${lineno}d" "$file"  > /tmp/profile_final.$PID
			check_rc

			mv -f /tmp/profile_final.$PID "$file"
		done

	fi

	rc=1
	grep "export " "$file" | egrep " ${d_VAR}[ \t]+[a-zA-Z0-9_-]" >/dev/null 2>&1
	if [ "$?" = "0" ];then
		rc=0
	fi

	grep "export " "$file" | grep " ${d_VAR}$" >/dev/null 2>&1
	if [ "$?" = "0" ];then
		rc=0
	fi

	if [ "$rc" = "0" ];then
		sed -e "s/ ${d_VAR}//g" "$file" > /tmp/profile_final.$PID
		check_rc

		if [ -s /tmp/profile_final.$PID ];then
			mv -f /tmp/profile_final.$PID "$file"
		fi
	fi

}

del_cshlines()
{

csh_greplines_file="$1"
csh_upd_file_name="$2"

   if [ -s "$csh_greplines_file" ];then

      num_del_lines=0

      for lineno in `cat $csh_greplines_file`
      do

		firstline="$lineno"

		if [ "$linesdeleted" = "1" ];then
			
			[ "$lastline" -ge "$lineno" ] && continue

			if [ "${section_csh}" = "1" ];then

				firstline=`expr $lineno - $num_del_lines`
				num_del_lines=`expr $num_del_lines + 6`

			else

				firstline=`expr $lineno - $num_del_lines`
			#	num_del_lines=`expr $num_del_lines + 4`

			fi
		fi


		if [ "${section_csh}" = "1" ];then

			lastline=`expr $firstline + 5`
			[ "$num_del_lines" -eq 0 ] && num_del_lines=6

		else

			lastline=`expr $firstline + 3`
			[ "$num_del_lines" -eq 0 ] && num_del_lines=4

		fi

		if [ "$firstline" -ne 0 -a "$lastline" -ne 0 ];then
			sed -e  ""$firstline","$lastline"d" "$csh_upd_file_name" >/tmp/profile1.$PID 2>/dev/null

			if [ "$?" -eq 0 ];then
				cat /tmp/profile1.$PID > "$csh_upd_file_name"
				linesdeleted="1"
			fi
		fi

      done
    fi #end if -s $csh_greplines_file
}

#+----------------------------------------------------------------------------+
#| Input Paramters:                                                           |
#|         upd_var: This is the install directory to update (CAIGLBL0000)     |
#|   upd_file_name: The login profile to update (/etc/csh.login, /etc/profile)|
#|                                                                            |
#|     Called From: set_to_update_profile_csh_CA                              |
#+----------------------------------------------------------------------------+
rm_ca_env_csh()
{
	upd_file_name="$1"
	section_csh=""
	reg_section_csh=""

		upd_var="$2"
		firstline=0
		lastline=0

		rm -f /tmp/cai_mod.$PID 2>/dev/null

		#velsu01

		sed -e "/if ( \"\$CA_SECTION\" == \"minimum\" && ( $upd_var != \"\" ) ) exit 0/d" "$upd_file_name" > /tmp/profile_found.$PID 2>/dev/null
		
		[ "$?" = "0" ] && mv -f /tmp/profile_found.$PID "$upd_file_name"

		#velsu01

		if [ -s "$upd_file_name" ];then

			if [ "${section_variable}" != "" ];then
				if [ "$upd_var" = "" ];then

					grep -n "if.*== \"${section_variable}\" ) && ( " "$upd_file_name" |cut -d ':' -f1 >/tmp/cai_mod.$PID 2>/dev/null

				else

					grep -n "if.*== \"${section_variable}\" ) && ( ${upd_var} " "$upd_file_name" |cut -d ':' -f1 >/tmp/cai_mod.$PID 2>/dev/null

				fi

				[ -s /tmp/cai_mod.$PID ] && section_csh="1"
			else

			  if [ ! -s /tmp/cai_mod.$PID -a "$upd_var" != "" ];then

				grep -n "if.*&& ( ${upd_var} " "$upd_file_name" |cut -d ':' -f1 >/tmp/cai_mod.$PID 2>/dev/null
				
				if [ ! -s /tmp/cai_mod.$PID ];then

					grep -n "$upd_var" "$upd_file_name" |grep -v "${upd_var}[a-zA-Z0-9_-]" | grep -v "[a-zA-Z0-9_-]${upd_var}" | cut -d ':' -f1 >/tmp/cai_mod.$PID 2>/dev/null

					[ -s /tmp/cai_mod.$PID ] && reg_section_csh="1"

				else
					
					section_csh="1"

				fi # ! -s /tmp/cai_mod.$PID

			   fi #! -s /tmp/cai_mod.$PID -a "$upd_var" != "" ]

			fi # "${section_variable}" != ""

		fi # -s "$upd_file_name"


		del_cshlines /tmp/cai_mod.$PID "$upd_file_name"

		if [ "${section_variable}" != "" ];then

			rm -f /tmp/cai_mod.$PID 2>/dev/null

			grep -n "if.*&& ( ${upd_var} " "$upd_file_name" |cut -d ':' -f1 >/tmp/cai_mod.$PID 2>/dev/null

			if [ ! -s /tmp/cai_mod.$PID ];then
				grep -n "$upd_var" "$upd_file_name" |grep -v "${upd_var}[a-zA-Z0-9_-]" | grep -v "[a-zA-Z0-9_-]${upd_var}" | cut -d ':' -f1 >/tmp/cai_mod.$PID 2>/dev/null
				[ -s /tmp/cai_mod.$PID ] && del_cshlines /tmp/cai_mod.$PID "$upd_file_name"
			fi

	fi

    $AWK 'NF > 0' "$upd_file_name" > /tmp/profile1.$PID 2>/dev/null
    if [ "$?" -eq 0 ];then
       cat /tmp/profile1.$PID > "$upd_file_name"
    fi

    rm -f /tmp/profile1.$PID 2>/dev/null
    rm -f /tmp/cai_mod.$PID 2>/dev/null
}

del_var_csh()
{

rm_ca_env_csh "$update_file" "$variable"

return 0
}

rm_profile_CA()
{
fail_rc=0

	prof_list="/etc/profile $HOME/.profile"

	for profile_file in $prof_list
	do

		if [ -f "$profile_file" ];then

			sed -e "/\. \/etc\/profile.CA/d" "$profile_file" > /tmp/profile.tmp.$PID 2>/dev/null
			src="$?"

			if [ "$src" != "0" ];then
				fail_rc=1
			fi

			if [ "$src" = "0" -a -s /tmp/profile.tmp.$PID ];then

			  cat /tmp/profile.tmp.$PID > "$profile_file"
			fi

			rm -f /tmp/profile.tmp.$PID 2>/dev/null
		fi
	done
return $fail_rc
}

rm_csh_login_CA()
{
fail_rc=0

	for csh_login in /etc/cshrc /etc/.login /etc/login.csh /etc/csh.login
	do
	  if [ -f "$csh_login" ];then
		sed -e "/source \/etc\/csh_login.CA/d" "$csh_login" > /tmp/csh_login.tmp.$PID 2>/dev/null
		src="$?"
		
		if [ "$src" != "0" ];then
			fail_rc=1
		fi

		if [ "$src" = "0" -a -s /tmp/csh_login.tmp.$PID ];then
			cat /tmp/csh_login.tmp.$PID  > "$csh_login"
		fi

		rm -f /tmp/csh_login.tmp.$PID 2>/dev/null
	  fi
	done

return $fail_rc
}

rm_ca_files()
{
    if [ ! -s /etc/profile.CA ];then
        rm_profile_CA
        prc="$?"

        if [ "$prc" = "0" ];then
            rm -f /etc/profile.CA 2>/dev/null
        fi
    fi


    if [ ! -s /etc/csh_login.CA ];then
        rm_csh_login_CA
        crc="$?"

        if [ "$crc" = "0" ];then
            rm -f /etc/csh_login.CA 2>/dev/null
        fi
    fi

    return 0
}

upd_env_variable()
{
  variable_to_upd="$1"
  sh_script_to_upd="$2"
  csh_script_to_upd="$3"

	# for update scenario remove ca updates
	for login_prof in /etc/profile $HOME/.profile /etc/cshrc /etc/.login /etc/login.csh /etc/csh.login
	do
		if [ -f "$login_prof" ];then
		  rm_ca_var_update "$variable_to_upd" "$login_prof"
		fi
	done

	#update /etc/profile
	update_env_profile "$variable_to_upd" "$sh_script_to_upd"

	#update cshell scripts
	update_env_csh "$variable_to_upd" "$csh_script_to_upd"

}

set_variable()
{

	variable="$1"
	file_CA="$2"
	envusr_loc="$3"

	eval variable_value='$'$variable

	[ "$variable_value" = "" ] && 
	{
		restoreOriginalPermissions
		rm_tmpfiles
		exit 120
	}

	space_in_dir=""

	$ECHO "${variable_value}" |grep " " >/dev/null 2>&1
	[ "$?" = "0" ] && space_in_dir="1"

    if [ "$file_CA" = "/etc/profile.CA" ]; then

		[ "$section_set" = "1" ] && \
			$ECHO "if [ \\( \"\$CA_SECTION\" = \"all\" -o \"\$CA_SECTION\" = \"${section_variable}\" \\) -a ${env_var} ];then #Sets ${env_var} variable within the ${section_variable} section" >> "$file_CA"

		if [ "$space_in_dir" = "1" ];then
			$ECHO "${variable}=\"${variable_value}\"; export ${variable}" >> "$file_CA"
		else
			$ECHO "${variable}=${variable_value}; export ${variable}" >> "$file_CA"
		fi

        if [ "$envusr_loc" != "" ];then
			$ECHO "if [ -f \"\$${variable}/${envusr_loc}\" ];then" >> "$file_CA"
			$ECHO "     . \"\$${variable}/${envusr_loc}\"" >> "$file_CA"
			$ECHO "fi" >> "$file_CA"	
        fi

	[ "$section_set" = "1" ] && $ECHO "fi" >> "$file_CA"

	#velsu01
	
	if [ "$variable" = "CASHCOMP" ];then 	
		$ECHO "[ \"\$CA_SECTION\" = \"minimum\" -a CASHCOMP ] && return 0" >> "$file_CA"
	fi		
	#velsu01

    elif [ "$file_CA" = "/etc/csh_login.CA" ]; then

		[ "$section_set" = "1" ] && \
			$ECHO "if ( ( \"\$CA_SECTION\" == \"all\" || \"\$CA_SECTION\" == \"${section_variable}\" ) && ( ${env_var} != \"\" ) ) then" >> "$file_CA" 

        if [ "$envusr_loc" != "" ];then


			if [ "$space_in_dir" = "1" ];then
				$ECHO "setenv ${variable} \"${variable_value}\"" >> "$file_CA"
			else
				$ECHO "setenv ${variable} ${variable_value}" >> "$file_CA"	
			fi

			$ECHO "if ( -f \"\$${variable}/${envusr_loc}\" ) then"  >> "$file_CA"
			$ECHO "    source \"\$${variable}/${envusr_loc}\"" >> "$file_CA"
			$ECHO "endif" >> "$file_CA"
			

        else
            $ECHO "# ${variable} update" >> "$file_CA"
            $ECHO "# ${variable} is now being set." >> "$file_CA"
            $ECHO "# Please do not edit this file in anyway." >> "$file_CA"
			if [ "$space_in_dir" = "1" ];then
				$ECHO "setenv ${variable} \"${variable_value}\"" >> "$file_CA"
			else
				$ECHO "setenv ${variable} ${variable_value}" >> "$file_CA"	
			fi
        fi


	[ "$section_set" = "1" ] && $ECHO "endif"  >> "$file_CA"

	#velsu01	
	
	if [ "$variable" = "CASHCOMP" ];then
		$ECHO "if ( \"\$CA_SECTION\" == \"minimum\" && ( CASHCOMP != \"\" ) ) exit 0" >> "$file_CA"
	fi
	#velsu01

    fi
}

update_profile_CA()
{

variable="$1"
file_CA="$2"
envusr_loc="$3"

eval variable_value=$`$ECHO $variable`
if [ "$variable_value" = "" ];then
    return 1
fi

[ "$file_CA" != "/etc/profile.CA" -a "$file_CA" != "/etc/csh_login.CA" ] && { restoreOriginalPermissions; exit 4; }


	if [  "$file_CA" = "/etc/csh_login.CA" -a -f "/etc/csh_login.CA" ];then

		if [ "${section_variable}" != "" ];then

			grep -n "if.* || \"\$CA_SECTION\" == \"${section_variable}\" ) && ( ${upd_var} " "$file_CA" |cut -d ':' -f1 >/tmp/var_ifln_file.$PID
			
			[ -s "/tmp/var_ifln_file.$PID" ] && return 0
		
			
		fi

	fi

    if [ -f "$file_CA" ];then

        if [ "$variable" = "CASHCOMP" -o "$variable" = "CABIN" -o "$variable" = "CALIB" ];then
            cp -pf "$file_CA" "${file_CA}.tmp" 2>/dev/null
            rc_cp="$?"

            if [ "${rc_cp}" = "0" ];then
                    rm -f "$file_CA" 2>/dev/null
            fi
        fi

    fi
	set_variable "$variable" "$file_CA" "$envusr_loc"
#saitu01 start Issue:17755738
	if [ "$variable" = "CABIN" -o "$variable" = "CALIB" ]; then
		sed -n '1!G;h;$p' "$file_CA" >> "${file_CA}.tmp1"
		 rc_sed="$?"
               if [ "${rc_sed}" = "0" ];then
                    mv "${file_CA}.tmp1" "$file_CA"
                    rm -f "${file_CA}.tmp1" 2>/dev/null
               fi
		while read linevar
		do
		sed -e '/"\$CA_SECTION" = "minimum"/ a\
'"$linevar"'' "${file_CA}.tmp" >> "${file_CA}.tmp1" 2>/dev/null
		rc_sed="$?"
     	       if [ "${rc_sed}" = "0" ];then
		    mv "${file_CA}.tmp1" "${file_CA}.tmp"	
                    rm -f "${file_CA}.tmp1" 2>/dev/null
       	       fi
		done < "$file_CA"
		rc_cp="$?"
		if [ "${rc_cp}" = "0" ];then
                    rm -f "$file_CA" 2>/dev/null
            fi
	mv "${file_CA}.tmp" "$file_CA"	
	fi
#saitu01 end Issue:17755738
	if [ "$variable" = "CASHCOMP" -a "$rc_cp" = "0" ];then

		[ -f "${file_CA}.tmp" ] &&	cat "${file_CA}.tmp" >> "$file_CA"

	fi

    rm -f /tmp/pub_file.$PID /tmp/priv_file.$PID /tmp/pr_line.$PID "${file_CA}.tmp" 2>/dev/null

}

set_to_update_profile_csh_CA()
{
variable="$1"
update_file="$2"

if [ "$update_file" = "/etc/profile.CA" ];then

	# Remove updates from /etc/profile
        grep "${variable}=" /etc/profile > /tmp/ca_tmp_file.$PID 2>/dev/null
	
	if [ "$?" = "0" ];then
		del_var_bash "$variable" /etc/profile
	fi

	if [ -f "$update_file" ];then

		grep -n "if[ \t]*\[.* -a ${env_var}[ \t]*\]" "$update_file" |grep -v "\#[ \t]*if" >/dev/null 2>&1
		rcg1="$?"

		if [ "$rcg1" != "0" ];then
			grep "${variable}=" "$update_file" > /tmp/ca_tmp_file.$PID 2>/dev/null
			rcg1="$?"
		fi

        # if found remove $variable references from /etc/profile.CA
        if [ "$rcg1" = "0" ];then

			del_var_bash "$variable" "$update_file"

			$AWK 'NF > 0' "$update_file" > /tmp/profile1.$PID

			[ "$?" = "0" ] && mv -f /tmp/profile1.$PID "$update_file" 2>/dev/null

			rm -f /tmp/profile1.$PID 2>/dev/null
				
        fi
	fi
elif [ "$update_file" = "/etc/csh_login.CA" ];then

	if [ -f "$update_file" ];then

        grep "setenv ${variable} " "$update_file" > /tmp/ca_tmp_file.$PID 2>/dev/null

        # if found remove $variable references from /etc/csh_login.CA
        if [ "$?" -eq 0 ];then
            rm_ca_env_csh "$update_file" "$variable" 
        fi
	fi
fi

rm -f /tmp/ca_tmp_file.$PID 2>/dev/null
}

update_envusr()
{
variable="$1"
update_file_usr="$2"
env_shell="$3"

set_to_update_profile_csh_CA  "$variable" "$update_file_usr"

# now update profile.CA or csh_login.CA with current variable
update_profile_CA "$variable" "$update_file_usr" "$env_shell" 

rm -f /tmp/ca_tmp_file.$PID >/dev/null 2>&1
} # end of update_envusr()

update_env_profile()
#+---------------------------------------------------------------------------+
#| Function:    update_env_profile                                           |
#|                                                                           |
#| Description: Update everyone's login profile (non c-shell)                |
#|              If user requests profile update check to see if there was a  |
#|              prior CA update that was commented out                       |
#|                                                                           |
#| Input:       Environment Variable to update (ie CAIGLBL0000 JI_SYSTEM     |
#|              Login scripts to be updated (ie /etc/profile)                |
#+---------------------------------------------------------------------------+
{
	variable="$1"
	env_shell="$2"

	ProfileUpdateLine="test -r /etc/profile.CA && { CA_SECTION=ccs; export CA_SECTION; . /etc/profile.CA; unset CA_SECTION; } # Added by Computer Associates"
#saitu01 removing user Home profile Issue:17755738 Porting from 11.0 to 11.2
	prof_list="/etc/profile"

	if [ "$Update_Profile" = "1" ];then

		for prof_file in $prof_list
		do
			if [ -f "$prof_file" ];then

				# create backup files, added as a request from a customer issue
				if [ "$CAPROFILE_BACKUP_PROFILES" = "1" ];then
					if [ ! -f "${prof_file}.ccsbackup" ];then
						cp -p "${prof_file}" "${prof_file}.ccsbackup"
					fi
				fi
							
				rm -f /tmp/profile.tmp.$PID 2>/dev/null
				grep -v "\#.*\. \/etc\/profile.CA" "$prof_file" > /tmp/profile.tmp.$PID 2>/dev/null
				if  [ "$?" -eq 0 -a -s /tmp/profile.tmp.$PID ];then
					mv -f "/tmp/profile.tmp.$PID" "$prof_file"
				fi

				# if the script is empty, just update it
				if [ ! -s "$prof_file" ];then
					$ECHO "$ProfileUpdateLine" >> "$prof_file"
					$ECHO "" >> "$prof_file"
				else
					sed -e "/\. \/etc\/profile.CA/d" "$prof_file" > /tmp/profile.tmp.$PID 2>/dev/null
					if  [ "$?" = "0" -a -s /tmp/profile.tmp.$PID ];then

						$ECHO "$ProfileUpdateLine" >> "/tmp/profile.tmp.$PID"
						mv -f "/tmp/profile.tmp.$PID" "$prof_file"

					fi
				fi

			fi 
		done

	fi #end if $Update_Profile = "1"

	update_envusr $variable /etc/profile.CA "$env_shell" 

	rm -f /tmp/profile.tmp.$PID 2>/dev/null
} # end of update_env_profile()

update_env_csh()
{
#+---------------------------------------------------------------------------+
#| Function:    update_env_csh                                               |
#|                                                                           |
#| Description: Update everyone's csh profile? (Update $csh_login)           |
#|              If user requests profile update check to see if there was a  |
#|              prior CA update that was commented out                       |
#|                                                                           |
#| Input:       Environment Variable to update (ie CAIGLBL0000 JI_SYSTEM     |
#|              Login scripts to be updated (ie /etc/csh_login)              |
#+---------------------------------------------------------------------------+
	variable="$1"
	env_shell="$2"

	CshUpdateLine='setenv CA_SECTION ccs; if ( -r /etc/csh_login.CA ) source /etc/csh_login.CA; unsetenv CA_SECTION # Added by Computer Associates'

	if [ "$Update_Profile" = "1" ];then

		for csh_login in /etc/cshrc /etc/.login /etc/login.csh /etc/csh.login
		do

		  if [ -f "$csh_login" ];then

				# create backup files, added as a request from a customer issue
				if [ "$CAPROFILE_BACKUP_PROFILES" = "1" ];then
					if [ ! -f "${csh_login}.ccsbackup" ];then
						cp -p "${csh_login}" "${csh_login}.ccsbackup"
					fi
				fi

				sed -e "/\#.*source \/etc\/csh_login.CA/d" "$csh_login" > /tmp/csh_login.tmp.$PID 2>/dev/null

				if [ "$?" -eq 0 -a -s /tmp/csh_login.tmp.$PID ];then
					mv -f /tmp/csh_login.tmp.$PID "$csh_login"
				fi


				# if the script is empty, just update it
				if [ ! -s "$csh_login" ];then
					$ECHO "$CshUpdateLine" >> "$csh_login"
					$ECHO "" >> "$csh_login"
				else
					sed -e "/source \/etc\/csh_login.CA/d" "$csh_login" > /tmp/csh_login.tmp.$PID 2>/dev/null
					if  [ "$?" = "0" -a -s /tmp/csh_login.tmp.$PID ];then
						$ECHO 'setenv CA_SECTION ccs; if ( -r /etc/csh_login.CA ) source /etc/csh_login.CA; unsetenv CA_SECTION # Added by Computer Associates' >> /tmp/csh_login.tmp.$PID
						mv -f /tmp/csh_login.tmp.$PID "$csh_login"
						
					fi
				fi

		  fi  # end if csh_login

		done # end of update csh files

	fi # end if Update_Profile = "1"

	update_envusr $variable /etc/csh_login.CA "$env_shell" 

	rm -f /tmp/csh_login.tmp.$PID 2>/dev/null
} #end of update_env_csh

Chk_Dir_Perms()
{

	[ "$Query" = "1" ] && return 0

	create_dir=""

	qvar="$1"
	eval q_var_val="$"`$ECHO $qvar`""

	if [ ! -d "${q_var_val}" ];then
		mkdir -p "${q_var_val}" 2>/dev/null
		if [ "$?" != "0" ];then
			#cannot create the directory
			return 114
		fi

		create_dir="1"
	fi
	
	touch "${q_var_val}/.tmp" 2>/dev/null
	if [ "$?" != "0" ];then
		#cannot create files in the directory
		return 115
	else

		rm -f "${q_var_val}/.tmp" 2>/dev/null

		# try to remove what we created
		[ "$create_dir" = "1" ] && rmdir "${q_var_val}" 2>/dev/null

		return 0
	fi
}


Chk_Env_in_Profile()
{
qvariable="$1"
qvar_value=""

 for file in /etc/profile /etc/profile.CA
 do
	if [ -f "$file" ];then
		vals_qvar=`grep "${qvariable}=" "$file" |egrep -v "[a-zA-Z0-9_-]${qvariable}=" |\
			 egrep -v "\#[ \t]*${qvariable}" | $AWK -F"${qvariable}=" '{print $2}'| $AWK -F\; '{print $1}'`


		rm -f "/tmp/rvalue.${PID}" 2>/dev/null

		echo "$vals_qvar" |while [ 1 ]
		do
			read rvalue	
			
			# variable's value is not set once we leave this loop, so adopt temp file method.
			[ "$rvalue" = "" ] && break || echo "$rvalue" > /tmp/rvalue.$PID
		done	

		[ -f "/tmp/rvalue.$PID" ] && qvar_value="`cat /tmp/rvalue.${PID}`"

	fi
 done

 # Remove temporary file created
 rm -f "/tmp/rvalue.${PID}" 2>/dev/null

 if [ "$qvar_value" = "" ];then
	return 116
 else
	eval "$qvariable"=$qvar_value
	export "$qvariable"

	return 0

 fi
}

Chk_SpecialVar()
{
	# only allowed args are CALIB and CABIN

	qvar="$1"

	Chk_Env_in_Profile CASHCOMP

	Chk_Env_in_Profile "$qvar"
	eval q_var_val="$"`$ECHO $qvar`""

	case "$qvar" in
	 "CALIB" )	
		subdir="lib" 
		if [ "${CASHCOMP}/${subdir}" != "$q_var_val" ];then
			return 110
		fi

		;;

	 "CABIN" )
		subdir="bin"
		if [ "${CASHCOMP}/${subdir}" != "$q_var_val" ];then
			return 111
		fi

		#Chk_Dir_Perms CABIN
		#return $?

		;;
	esac

}

Chk_RegularVar()
{
	qvar="$1"

	Chk_Env_in_Profile "$qvar"
	rc1=$?
	if [ "$rc1" != "0" ];then
		return $rc1
	fi

	eval q_var_val='$'$qvar

	if [ "$q_var_val" != "" ];then
		$ECHO "$q_var_val"
		return 0
	else
		return 113
	fi
}

get_pid()
{
PID="$$"

if [ `uname` = "Linux" ];then

	TMP_FILE="`mktemp /tmp/prof_XXXXXXXXXX 2>/dev/null`" || exit 1 

	PID="`basename ${TMP_FILE}`.${PID}"

	rm -f "${TMP_FILE}" 2>/dev/null
else
	PID1=`expr $PID + 52638`
	PID="prof_${PID}$PID1"
fi

return 0
}

QueryVariable()
{
	qvar="$1"

	case "$qvar" in
	"CASHCOMP" ) Chk_Env_in_Profile CASHCOMP
			CASH_rc="$?"

			if [ "$CASH_rc" != "" ];then
				$ECHO "$CASHCOMP"
			fi

			return "$CASH_rc"
			;;

	*) 		Chk_RegularVar "$qvar"
			return $?;;
	esac
}

Chk_Root()
{
	# make sure we are running as root
	#id=`id | cut -c1-11`
	#if [ "uid=0(root)" != "$id" ]; then
	#	exit 5
	#fi
	
	# velsu01: check for user id 0 rather than for the string 0(root)
	# uid=`id root | sed 's/.*uid=\([0-9]*\).*/\1/'`
        # rosvi01: check for the uid of actual user running the script 
	uid=`id | sed 's/.*uid=\([0-9]*\).*/\1/'`
	if [ "$uid" != "0" ];then
		exit 5
	fi
}

# Convert previous versions of profile.CA and csh__login.CA using $1 to $CA_SECTION
conv_arg1_ca_section()
{

	for file1 in /etc/profile.CA /etc/csh_login.CA
	do

		[ -f "$file1" ] && {
			sed -e 's/\$1/\$CA_SECTION/g' $file1 > /tmp/setting_sh.$PID
			[ "$?" = "0" ] && mv -f /tmp/setting_sh.$PID $file1
		}
	done

	rm -f /tmp/setting_sh.$PID 2>/dev/null
}

set_start_setting()
{

	if [ -f /etc/profile.CA ];then

		rm -f /tmp/setting_sh.$PID 2>/dev/null

		# Set start setting
		$ECHO 'CA_SECTION=${CA_SECTION:-${1:-}}; export CA_SECTION #Set CA_SECTION to the first argument' > /tmp/setting_sh.$PID
		$ECHO 'CA_ETC_CAPROFILE() {' >> /tmp/setting_sh.$PID

		#first remove the existing CA_SECTION entry and CA_ETC_CAPROFILE()
		sed -e '/CA_SECTION=${/d' -e '/CA_ETC_CAPROFILE()/d' /etc/profile.CA >> /tmp/setting_sh.$PID
		[ "$?" = "0" ] && mv -f /tmp/setting_sh.$PID /etc/profile.CA

		rm -f /tmp/setting_sh.$PID 2>/dev/null
	fi

	if [ -f /etc/csh_login.CA ];then

		rm -f /tmp/setting_sh.$PID 2>/dev/null	

		# Set start setting
		$ECHO 'if ( ( $?CA_SECTION ) && ( "$1" != "" ) ) setenv CA_SECTION $1; if ( ! $?CA_SECTION ) setenv CA_SECTION "" #Set CA_SECTION to the first argument' > /tmp/setting_sh.$PID

		sed -e "/setenv CA_SECTION /d" /etc/csh_login.CA >> /tmp/setting_sh.$PID
		[ "$?" = "0" ] && mv -f /tmp/setting_sh.$PID /etc/csh_login.CA

		rm -f /tmp/setting_sh.$PID 2>/dev/null	
		
	fi

}

del_start_end_setting()
{
	if [ -f /etc/profile.CA ];then
		rm -f /tmp/setting_sh.$PID 2>/dev/null
		
		sed -e '/CA_SECTION=${/d' -e '/CA_ETC_CAPROFILE()/d' -e '/}; CA_ETC_CAPROFILE/d' /etc/profile.CA >> /tmp/setting_sh.$PID
		[ ! -s /tmp/setting_sh.$PID ] && rm -f /etc/profile.CA
		rm -f /tmp/setting_sh.$PID 2>/dev/null
	fi

	if [ -f /etc/csh_login.CA ];then
		rm -f /tmp/setting_sh.$PID 2>/dev/null
		
		sed -e "/setenv CA_SECTION /d" /etc/csh_login.CA >> /tmp/setting_sh.$PID
		[ ! -s /tmp/setting_sh.$PID ] && rm -f /etc/csh_login.CA
		rm -f /tmp/setting_sh.$PID 2>/dev/null
	fi
}


# Set this code at the end to return back to the system settings
set_end_setting()
{

	rm -f /tmp/setting_sh.$PID
	if [ -f /etc/profile.CA ]; then

		sed -e '/}; CA_ETC_CAPROFILE/d' /etc/profile.CA >> /tmp/setting_sh.$PID
		if [ "$?" = "0" ]; then
			$ECHO '}; CA_ETC_CAPROFILE $CA_SECTION' >> /tmp/setting_sh.$PID
			mv -f /tmp/setting_sh.$PID /etc/profile.CA
		fi
	fi



	# set these flags only when setting CASHCOMP
	QueryVariable CASHCOMP >/dev/null 2>&1

	[ "$?" = "0" ] && {


		 for env_var in CACSUTILS_setu CANOLOG_flag
		 do
			for file2 in /etc/profile.CA /etc/csh_login.CA
			do
				set_to_update_profile_csh_CA "$env_var" "$file2"
			done
		 done


		if [ -f /etc/profile.CA ];then

			$ECHO '[ "${CANOLOG_flag:-${CANOLOG_flag:-}}" = "off" ] && set +o nolog; CANOLOG_flag="" # return to system setting' >> /etc/profile.CA

			$ECHO '[ "${CACSUTILS_setu:-${CACSUTILS_setu:-}}" = "1" ] &&  set -u; CACSUTILS_setu="" # return to system setting' >> /etc/profile.CA

		fi

		if [ -f /etc/csh_login.CA ];then
			# add section for csh_login.CA for CANOLOG_flaf and CA_CSUTILS_setu
			:
		fi

	} #end "$CASHCOMP" != ""

}

rm_tmpfiles()
{
	#remove temporary files
	rm -f /tmp/filn_file.* /tmp/ifln_file.* /tmp/var_ifln_file.* /tmp/filn_file.* /tmp/profile_found.* /tmp/profile_final.* 2>/dev/null
	rm -f /tmp/mod_file2del.* /tmp/cai_mod.* /tmp/jpriv_file.* /tmp/gpub_file.* /tmp/pr_line.* /tmp/profile1.* 2>/dev/null
}

Use_caprofile_in_CASHCOMP()
{
	Chk_Env_in_Profile CASHCOMP >/dev/null
	
	if [ "x$CASHCOMP" != "x" -a \
		-f "${CASHCOMP}/csutils/bin/caprofile" ];then 

		CAPROFILE_RUNONCE=1; export CAPROFILE_RUNONCE

		/bin/sh "${CASHCOMP}/csutils/bin/caprofile" "$@"
		exit $?
	fi
}

FixSettings()
{
	#Set CA_SECTION to $1 if it is null, at the start of the settings
	set_start_setting

	# Set this code at the end to return back to the system settings
	set_end_setting

	for file2 in /etc/profile.CA /etc/csh_login.CA
	do
		chmod 644 "$file2" 2>/dev/null
	done
}

# MAINLINE
#

#setup ECHO first
  if [ `uname` = "Linux" ];then
     ECHO="echo -e"
  else
     ECHO="echo"
  fi
export ECHO

# get a safe pid
get_pid
CURRDIR="`pwd`"

dir_name="`dirname $0`"
pgm_name="`basename $0`"

#[ "$dir_name" = "." ] && dir_name="$CURRDIR"
#if [ "`echo $dir_name | cut -c1-2`" = ".." ];then
	cd "$dir_name"
	dir_name="`pwd`"
	cd "$CURRDIR"
#fi
	

 if [ "$#" -lt 1 ];then
	#Comments

	#$ECHO "Insufficient arguments passed to $pgm_name"
	#$ECHO "Exiting."
	exit 3
 fi

 if [ -x /usr/bin/nawk ];then
   AWK=/usr/bin/nawk
 elif [ -x /bin/gawk ];then
   AWK=/bin/gawk
 elif [ -x /usr/bin/gawk ];then
   AWK=/usr/bin/gawk
 elif [ -x /usr/local/bin/gawk ];then
   AWK=/usr/local/bin/gawk
 else
   AWK=awk
 fi

 #initialize temp vars
 upd_sh=""
 upd_csh=""

 [ "$Update_Profile" = "" ] && Update_Profile="1"
 
 [ "$CAPROFILE_BACKUP_PROFILES" = "" ] && CAPROFILE_BACKUP_PROFILES="1"

 #number of arguments
 num_args=$#
 
 all_args="$@"

	my_name="$dir_name"/"$pgm_name"

	if [ -h "$my_name" ];then
		my_name="`ls -l \"$my_name\" | $AWK -F' -> ' '{ print $2 }'`"
	fi

	#echo "my_name=$my_name"

	if [ "$my_name" != "${CASHCOMP}/csutils/bin/caprofile" ]; then
		# velsu01:
		# By default, this caprofile script will execute $CASHCOMP/csutils/bin/caprofile
		# if it exists. This is to prevent products embedding caprofile to have an
		# adverse affect on the setting of variables in profile_CA.
		# To override this behavior and to always use the current script, set
		# CAPROFILE_OVERRIDE=1 in your environment prior to this script execution.

		if [ "$CAPROFILE_OVERRIDE" != "1" -a "$CAPROFILE_RUNONCE" != "1" ];then
			#echo "using caprofile in CASHCOMP"
			Use_caprofile_in_CASHCOMP "$@"
		fi
	fi

	# get the option
	option="$1"

	# Get current permission setting for standard system environment setup scripts
	getCurrentPermissions

	LINUX_GAWK_SUP="1"

	if [ -f /etc/redhat-release ];then
		LINUX_GAWK_SUP="0"
	fi


   crc=0
   case $option in
	"-s" )  Chk_Root


			optcnt=0
			optargcnt=0

			 while [ ${optargcnt} -le 7 ]
			 do
				eval argname="$`$ECHO ${optcnt}`"

				if [ "$argname" = "-private" ];then

					[ "$section_set" = "1" ] && exit 25

					private="1"

					section_argcnt="${optcnt}"

					optcnt=`expr ${optcnt} + 1`

					continue
				fi

				if [ "$argname" = "-section" ];then

					[ "$private" = "1" ] && exit 25

					[ "$option" != "-d" ] && [ "$optcnt" -gt 6 -o "$optcnt" -lt 3 ] && exit 20
					  
					section_set="1"
					section_argcnt="${optcnt}"

					nextarg_cnt=`expr ${optcnt} + 1`	
					eval section_variable="$`$ECHO ${nextarg_cnt}`"

					if [ "$section_variable" != "" ];then

						[ "$section_variable" = "-private" ] && exit 25

						first_bit="`$ECHO "$section_variable" |cut -c1`"
						
						case "$first_bit" in
						 "/" | "-" | " " ) exit 21;;
						esac
					else
						exit 20
					fi
				fi

				optcnt=`expr ${optcnt} + 1`

				[ "$argname" = "" ] && break

				eval opt${optargcnt}='${argname}'

				num_args="${optargcnt}"

				optargcnt=`expr ${optargcnt} + 1`

			 done

			 env_var="${opt2}"

			 [ "$section_set" = "1" ] && num_args=`expr ${num_args} - 2`

			 [ "$private" = "1" ] && \
			 {
				section_set="1"
				section_variable="$env_var"	
			 }

			if [ "$option" != "-d" ];then
			  case $num_args in 
				1 ) if [ "$option" != "-h" -a "$option" != "-?" ];then

					 exit 3

					fi;;

				2 )
					eval env_var_value="$"`$ECHO $env_var`""

					[ "$section_set" = "1" -a "$section_argcnt" != "3" ] && exit 20

					;;
				
				3 )
					env_var_value="${opt3}"

					[ "$section_set" = "1" -a "$section_argcnt" != "4" ] && exit 20

					eval $env_var='$env_var_value'
					export "$env_var"

					;;

				4 ) 
					eval env_var_value="$"`$ECHO $env_var`""

					[ "$section_set" = "1" -a "$section_argcnt" != "5" ] && exit 20

					upd_sh="${opt3}"

					upd_csh="${opt4}"

					;;

				5 )
					env_var_value="${opt3}"

					[ "$section_set" = "1" -a "$section_argcnt" != "6" ] && exit 20

					eval $env_var='$env_var_value'
					export "$env_var"

					upd_sh="${opt4}"

					upd_csh="${opt5}"

					;;
			  esac
			fi

			if [ $num_args -gt 5 ];then
				exit 3
			fi

			if [ "${env_var_value}" = "" ];then
				exit 6
			fi

			Chk_Env_in_Profile CASHCOMP >/dev/null

			sed -e "/if ( \"\$1\" != \"all\" )[ \t]*exit 0/d" /etc/csh_login.CA >/tmp/csh_login.tmp.$PID 2>/dev/null

			if [ "$?" -eq 0 -a -s /tmp/csh_login.tmp.$PID ];then
				cat /tmp/csh_login.tmp.$PID  > /etc/csh_login.CA
				rm -f /tmp/csh_login.tmp.$PID 2>/dev/null
			fi

			sed -e "/\[ \"\$CA_SECTION\" != \"all\" \][ \t]*\&\& return 0/d" /etc/profile.CA > /tmp/profile.tmp.$PID 2>/dev/null

			if [ "$?" -eq 0 -a -s /tmp/profile.tmp.$PID ];then
				cat /tmp/profile.tmp.$PID > /etc/profile.CA
				rm -f /tmp/profile.tmp.$PID 2>/dev/null
			fi

			case "${env_var}" in
			"CALIB" | "CABIN" )

				Chk_SpecialVar "${env_var}"
				crc=$?

				if [ "$crc" = "0" ];then
					CALIB=$CASHCOMP/lib
					export CALIB

					CABIN=$CASHCOMP/bin
					export CABIN

					upd_env_variable "${env_var}" "${upd_sh}" "${upd_csh}"
				else
					restoreOriginalPermissions
					rm_tmpfiles
					exit $crc
				fi;;
			"CASHCOMP" )

					upd_env_variable CASHCOMP "${upd_sh}" "${upd_csh}"

				;;
			
			"CA_SECTION" | "PATH" | "LD_LIBRARY_PATH" | "LIBPATH" | "SHLIB_PATH" | "MANPATH" ) ;;

			* ) 
				[ "$env_var_value" = "" ] && Chk_Env_in_Profile "${env_var}"

				upd_env_variable "${env_var}" "${upd_sh}" "${upd_csh}";;
			esac


			conv_arg1_ca_section

			FixSettings

			restoreOriginalPermissions
			rm_tmpfiles

			exit $crc;;

	"-q" )  Query="1"

			if [ $num_args -ne 2 ];then
				#$ECHO "Syntax: caprofile -q VARIABLE" 
				exit 3
			fi

			env_var=$2
			
			QueryVariable "$env_var"
			exit $?;;
	"-d" )  
			Chk_Root  

			if [ $num_args -lt 1 ];then
				#$ECHO "Syntax: caprofile -d VARIABLE" 
				exit 3
			fi

			shift 1
			rm_args="$@"

			argcnt=$# 
			tmp_cnt=1			
			while [ $tmp_cnt -le $argcnt ];do

				eval argname="$`$ECHO ${tmp_cnt}`"	
				tmp_cnt=`expr $tmp_cnt + 1`
				if [ "$argname" = "-section" ];then
					section_del_set=1
					continue
				fi

				if [ "$section_del_set" = "1" ];then
					if [ "$section_names" != "" ];then
						section_names="$section_names $argname"
					else
						section_names="$argname"
					fi
				else
					if [ "$variable_names" != "" ];then
						variable_names="$variable_names $argname"
					else
						variable_names="$argname"
					fi
				fi
			done

			delarg=1

			if [ "$section_del_set" = "1" ];then

				[ "$section_names" = "" ] && exit 20

				for section_variable in $section_names
				do
					if [ "$variable_names" = "" ];then	

						env_var=""; upd_var=""

						# Remove the whole $section_variable section
						del_ifln /etc/profile.CA
						rm_ca_env_csh /etc/csh_login.CA
					else
					
						for variable_name in $variable_names
						do
							case "$variable_name" in
							  "PATH" | "LD_LIBRARY_PATH" | "LIBPATH" | "SHLIB_PATH" | "MANPATH" ) continue;;
							esac

							env_var=$variable_name; upd_var=$variable_name

							# Remove the variable set within the section 
							del_ifln /etc/profile.CA "$env_var"
							rm_ca_env_csh /etc/csh_login.CA "$upd_var"

							for file2 in /etc/profile.CA /etc/csh_login.CA
							do
								[ "$env_var" = "CASHCOMP" ] && {

								   for delendvar in CACSUTILS_setu CANOLOG_flag
								   do
									set_to_update_profile_csh_CA "$delendvar" "$file2"
								   done
								}
							done
						done

					fi
					
				done
			
			else # else if "$section_del_set" != "1"

			  for del_var in $rm_args
			  do
			
				case "$del_var" in
				  "CA_SECTION" | "PATH" | "LD_LIBRARY_PATH" | "LIBPATH" | "SHLIB_PATH" | "MANPATH" ) continue;;
				esac

				env_var="$del_var"

				for file2 in /etc/profile.CA /etc/csh_login.CA
				do
					set_to_update_profile_csh_CA "$env_var" "$file2"

					[ "$env_var" = "CASHCOMP" ] && {

					   for delendvar in CACSUTILS_setu CANOLOG_flag
					   do
						set_to_update_profile_csh_CA "$delendvar" "$file2"
					   done
					}
				done

			  done
			
			fi # end if "$section_del_set" = "1"
			# shash10:: To Reset the /etc/profile.CA permissions			
			FixSettings

			del_start_end_setting
			rm_ca_files
			;;

    "-F" ) FixSettings ;;
    "-h" | "-?" )  Comments;;
	* ) #$ECHO "Invalid arguments"
		exit 3;;
  esac 

restoreOriginalPermissions
rm_tmpfiles

exit 0
