#!/bin/sh
# $Id$
# $Copyright: Copyright (c) 2022 Veritas Technologies LLC. All rights reserved $ 

# Set umask to 022 to make sure files and directories
# are not created with world writable permissions.
umask 022

#----- $Id$ -----
#
#		This function is a case statement sets
#		the ECHO variable
#		with the appropriate path & flags.

#Define Echo to allow escape characters
case "`uname -s`" in
	Linux*)
		unset POSIXLY_CORRECT
		ECHO="/bin/echo -e"
		;;
	SunOS*)
		ECHO="/usr/bin/echo"
		;;
	*)
		ECHO="echo"
		;;
esac
# Solaris's default awk doesn't support regex functions, but nawk does. Nawk
# isn't installed on all platforms, though. Let's use nawk when it's available,
# but awk otherwise. In order of preference:
#   /bin/nawk
#   /usr/bin/nawk
#   /usr/bin/awk
#
#  This logic is duplicated in nbcheck at
#  lib/NBCheck/NixPlatformCheck.pm.  Any change to the logic
#  here should be ported to nbcheck to keep the two components
#  synchronized.

AWK=/bin/nawk

if [ ! -f ${AWK} ] && [ -f /usr/bin/nawk ]; then
	AWK=/usr/bin/nawk
elif  [ ! -f ${AWK} ] && [ -f /usr/bin/awk ]; then
	AWK=/usr/bin/awk
fi

# vim: set ft=sh et sw=4 ts=4:
#----- $Id$
#
#  print_error is used in the native packaging control scripts
#  to display a message.  It expects one parameter:  the message
#  to be displayed.
#
#  Error messages should be in the peculiar format required by HP.
#  They must start with ERROR: and text message starts in column 10.
#  No blank lines or tabs in the message.  Message line cannot be
#  more than 72 characters or a new line must be started.  Second
#  line of a message must be indented to column 10.
#
#  ECHO is expected to be set already.

print_error ()
{
	if [ $# -ne 1 ] ; then
		${ECHO} "
ERROR:   Call to print_error has the wrong number of parameters."
		exit 1
	else
		# If the message text has any lines longer than 81 characters
		# (including the ERROR string or leading blanks), split them.
		${ECHO} "
ERROR:   ${1}
" | sed 's/\(.................................................................................\)/\1\
         /g'
	fi
}
# Read the configuration value(s) given by $2 from the file given in $1. The
# file should contain key=value pairs. Whitespace is ignored. Comments start
# with #. Whitespace surrounding the value is stripped before returning.
#
# Returns 0 if the key exists in the file. Prints the value to stdout. (If the
# key is present, but there's no value, then we print nothing, but still return
# 0.)
# Returns 1 if the key does not exist in the file, or if the file does not
# exist.
#
# Examples:
#
# Get name of master server
# read_first_config_value /usr/openv/netbackup/bp.conf SERVER
#
# Read answer file
# read_config_values /tmp/NBInstallAnswer.conf CA_CERTIFICATE_FINGERPRINT
#
# Requires fn.set_echo_var and fn.set_awk_var

__read_config_helper()
{
    config_file="${1}"
    key="${2}"
    filter="${3}"
    if [ ! -f "${config_file}" ]; then
        return 1
    fi
    result=`
        ${AWK} -v key="${key}" -F'[ \t]*=' '
        BEGIN { result = 227 }
        {
            sub("#.*", "", $0);
            if (match($1, "^[ \t]*" key "$")) {
                sub("^[^=]*=[ \t]*", "", $0);
                sub("[ \t]*$", "", $0);
                print;
                result = 0
            }
        }
        END { exit result }' "${config_file}"
    `
    if [ $? -ne 0 ]; then
        # no value specified
        return 1
    else
        # Filter
        ${ECHO} "${result}" | ${filter}
        return 0
    fi
}

read_config_values()
{
    __read_config_helper "$@" cat
}

read_first_config_value()
{
    __read_config_helper "$@" 'head -1'
}

read_last_config_value()
{
    __read_config_helper "$@" 'tail -1'
}

# vim: set ft=sh et sw=4 ts=4:
# Fetches service user value from bp.conf and sets it as nb_service_user.
#
# Checks whether the service user name exists in bp.conf. If the user does not exist, then it prints error.
#
# Returns 0 on success and sets $nb_service_user. Returns non-zero on failure.
#
# These functions are expected to be included already:
# print_error
# set_echo_var
# set_awk_var
# read_config_values

BP_CONF_FILE=/usr/openv/netbackup/bp.conf

get_service_user()
{
	nb_service_user=""

	if [ -f ${BP_CONF_FILE} ] ; then
		nb_service_user=`read_last_config_value ${BP_CONF_FILE} SERVICE_USER`
		if [ $? -ne 0 -o "${nb_service_user}" = "" ] ; then
			print_error "No daemon user was found in bp.conf."
			return 1
		else
			return 0
		fi
	else
		print_error "The configuration file (bp.conf) does not exist."
		return 1
	fi
}

#----- $Id$
#
#  Read value of bp.conf entry ALLOW_WORLD_READABLE_LOGS.
#
#  Returns:
#        0 if ALLOW_WORLD_READABLE_LOGS is set to FALSE/NO/0 or not defined in bp.conf.
#        1 if ALLOW_WORLD_READABLE_LOGS is set to TRUE/YES/1 in bp.conf.
#
#  Requires fn.read_config_values, fn.set_awk_var and fn.set_echo_var.

BP_CONF_FILE=/usr/openv/netbackup/bp.conf

allow_world_readable_logs()
{
    ALLOW_WORLD_READABLE_LOGS=0
    if [ -f ${BP_CONF_FILE} ] ; then
        ALLOW_WORLD_READABLE_LOGS=`read_last_config_value ${BP_CONF_FILE} ALLOW_WORLD_READABLE_LOGS | ${AWK} '{ print tolower($0) }'`
        if [ "${ALLOW_WORLD_READABLE_LOGS}" = "no" -o "${ALLOW_WORLD_READABLE_LOGS}" = "false" -o "${ALLOW_WORLD_READABLE_LOGS}" = "0" ] ; then
            ALLOW_WORLD_READABLE_LOGS=0
        elif [ "${ALLOW_WORLD_READABLE_LOGS}" = "yes" -o "${ALLOW_WORLD_READABLE_LOGS}" = "true" -o "${ALLOW_WORLD_READABLE_LOGS}" = "1" ] ; then
            ALLOW_WORLD_READABLE_LOGS=1
        else
            ALLOW_WORLD_READABLE_LOGS=0
        fi
    fi
}

BP_CONF_FILE=/usr/openv/netbackup/bp.conf

FTO_HARDENING_NVE60_PHASE2=0

# WWF process directory exception list.
wwf_exception=""

# NetBackup EOL component list.
eol_list="esfs_storage
	liveupdate
	nbacs
	nblastaging
	nbliveup
	nbrestoreec2
	ocsd_storage"

# NetBackup critical or runtime created component list.
critical_list="beds
	bmrb2vrst
	bmrFirstBoot
	bmrrst
	bpbrmvlt
	bpcoord
	bpdown
	bpinetd
	bpresolver
	dbeng11
	dbsrv11
	dbsrv9
	logging_tester
	nbcosp
	nbsmartdiag
	nbutil
	nbwin
	nbwdevice
	spsv2ra"

# Combined list of NetBackup's EOL and critical components.
eol_and_critical_dir_list="${eol_list} ${critical_list}"

# Exception list for user directories within the below list.
user_dir_exception="user_ops"

# Log list that will be created. 1 specifies that the directory will be enabled for non-root user logging.
# 1(in last bit) specifies that the directory will be owned by service user.
logs_list="admin;1;1
	backint;1;1
	bp;1;1
	bpVMreq;1;1
	bpVMutil;1;1
	bparchive;1;1
	bpbackup;1;1
	bpbkar;1;1
	bpbrm;0;0
	bpbrmds;0;1
	bpcd;0;0
	bpclimagelist;1;1
	bpclntcmd;1;1
	bpcompatd;0;1
	bpconverttouch;1;1
	bpdb2;1;1
	bpdbjobs;1;1
	bpdbm;0;1
	bpdbsbdb2;1;1
	bpdbsbora;1;1
	bpdhcp;1;1
	bpdm;0;1
	bpfilter;1;1
	bpfis;1;1
	bpfsmap;0;1
	bphdb;1;1
	bpinst;1;1
	bpjava-msvc;0;0
	bpjava-susvc;1;0
	bpjava-usvc;1;0
	bpjobd;0;1
	bpkeyutil;1;1
	bplist;1;1
	bpmount;1;1
	bpnbat;1;1
	bporaexp;1;1
	bporaexp64;1;1
	bporaimp;1;1
	bporaimp64;1;1
	bppfi;0;1
	bpps;1;1
	bprd;0;1
	bprestore;1;1
	bpstsinfo;1;0
	bpsynth;1;1
	bptestnetconn;1;1
	bptm;0;0
	cluster;1;1
	dbclient;1;1
	exten_client;1;1
	infxbsa;1;1
	mssql_backup_failures;1;1
	mtfrd;1;1
	nbaapidiscv;0;1
	nbaapireq_handler;0;1
	nbanomalyalert;0;1
	nbanomalydetect;0;1
	nbanomalymgmt;0;1
	nbauditreport;1;1
	nbazd;0;1
	nbcctd;1;1
	nbcert;1;1
	nbcssc;1;1
	nbdb;0;1
	nbdedupmts;0;1
	nbfp;0;1
	nbfsd;0;1
	nbhealthcheckcmd;1;1
	nbidmap;0;1
	nbidpcmd;1;1
	nbifs;1;1
	nbinstallagent;0;1
	nbinstallcmd;1;1
	nbjsonformat;0;1
	nbkmiputil;1;1
	nbkmscmd;1;1
	nblibcurlcmd;1;1
	nblogadm;1;1
	nblogadmagent;0;1
	nblogadmhelper;0;1
	nbmalwarescanner;0;1
	nbmsw;1;1
	nboraadm;1;1
	nborabkupsets;1;1
	nborair;1;1
	nbostpxy;1;1
	nbproxy;0;1
	nbregopsc;0;1
	nbrepo;0;1
	nbrecovervm;0;1
	nbrestorevm;1;1
	nbroute;1;1
	nbsqladm;1;1
	nbstop;1;1
	nbtelepush;0;1
	nbvault;0;1
	ncf;1;1
	patch;1;1
	spsdkservice;1;1
	sybackup;1;1
	symlogs;0;1
	tar;1;1
	user_ops;1;1
	user_ops/nbjlogs;1;0
	vault;1;1
	vnetd;0;1
	vxms;0;1"

if [ ${FTO_HARDENING_NVE60_PHASE2} -eq 1 ] ; then
	logs_list="${logs_list} nbpas;0;0"
fi

validate_command()
{
	cmd_r="$1"
	# Options that can be passed are represented below.
	if [ "${cmd_r}" != "" ] ; then
		if [ ${cmd_r} = "create" -o \
			${cmd_r} = "list" -o \
			${cmd_r} = "dryrun" -o \
			${cmd_r} = "fixFolderPerm" -o \
			${cmd_r} = "user" -o \
			${cmd_r} = "allowWW" -o \
			${cmd_r} = "savePrevPermissions" -o \
			${cmd_r} = "revertPermissions" ] ; then
			valid_cmd=1
		elif [ "${cmd_r}" = "help" ] ; then
			print_usage_and_exit
		else
			echo "Invalid Usage"
			print_usage_and_exit
		fi
	fi
}

print_usage_and_exit()
{
	echo "mklogdir [-create] [-dryrun] [logdirname ] [-user username]"
	echo "mklogdir -fixFolderPerm [-dryrun] [logdirname ]"
	echo "mklogdir -list"
	exit 22
}

# Processes the request passed either for all directories or for specific directories.
process_request()
{
	all=0
	if [ "$1" = "all" ] ; then
		# Going to be processing all directories.
		all=1
	else
		logdir=$1
	fi

	if [ ${create_req} -eq 1 ] ; then
		if [ ${all} -eq 1 ] ; then
			perform_op_all_log_dir "create"
		else
			perform_op_log_dir "create" "${logdir}"
		fi

	elif [ ${fixFolderPerm_req} -eq 1 ] ; then
		if [ ${all} -eq 1 ] ; then
			if [ ${savePrevPermisssions_req} -eq 1 ] ; then
				# Create a recovery file for storing existing file/folder permissions.
				# Users can refer to this file in case of an error.
				rm -f "${NBTMPDIR}/recoverPermissions.txt"
				touch "${NBTMPDIR}/recoverPermissions.txt"
			fi
			perform_op_all_log_dir "fixFolderPerm"
			if [ ${savePrevPermisssions_req} -eq 1 ] ; then
				if [ -f "${NBTMPDIR}/recoverPermissions.txt" ] ; then
					chmod 600 "${NBTMPDIR}/recoverPermissions.txt"
				else
					echo "Failed to create file ${NBTMPDIR}/recoverPermissions.txt"
					exit
				fi
			fi
		else
			perform_op_log_dir "fixFolderPerm" "${logdir}"
		fi
	else
		# This case will be encountered if user has specified mklogdir [logdirname].
		perform_op_log_dir "create" "${logdir}"
	fi
}

# Set directory list and permissions for creation task or fixing permissions.
set_dir_permission_list()
{
	dirname=$1
	dircreation_mode=$2
	dir_exception=0
	sub_dir_exception=0
	mk_user_dir=0
	# Check if directory name is in wwf exception list.
	for ex_dir in ${wwf_exception}
	do
		if [ "${ex_dir}" = "${dirname}" ] ; then
			dir_exception=1
			break
		fi
	done
	# Check if directory name is in user exception list.
	for ex_dir in ${user_dir_exception}
	do
		if [ "${ex_dir}" = "${dirname}" ] ; then
			sub_dir_exception=1
			break
		fi
	done
	if [ ${dircreation_mode} -eq 1 ] ; then
		if [ ${allowWW_req} -eq 0 -a ${dir_exception} -eq 0 ] ; then
			parentdircreationmode=0755
			mode_word="drwxr-xr-x"
			mk_user_dir=1
		else
			echo "${dirname} still with exception"
			parentdircreationmode=1777
			mode_word="drwxrwxrwt"
		fi
	else
		if [ ${ALLOW_WORLD_READABLE_LOGS} -eq 1 ] ; then
			parentdircreationmode=0755
			mode_word="drwxr-xr-x"
		else
			parentdircreationmode=0700
			mode_word="drwx------"
		fi
	fi
	if [ ${dircreation_mode} -eq 1 -a ${user_req} -eq 1 ] ; then
		if [ ${mk_user_dir} -eq 1 ] ; then
			dirname="${dirname} ${dirname}/${username}"
			# Get primary group id of the user.
			group_id=`id ${username} | ${AWK} -F"=" '{print $3}' | ${AWK} -F"(" '{print $1}'`
			if [ ${sub_dir_exception} -eq 0 ] ; then
				if [ ${ALLOW_WORLD_READABLE_LOGS} -eq 1 ] ; then
					subdircreationmode=0755
					sub_dir_mode_word="drwxr-xr-x"
				else
					subdircreationmode=0700
					sub_dir_mode_word="drwx------"
				fi
			else
				subdircreationmode=0755
				sub_dir_mode_word="drwxr-xr-x"
			fi
		fi
	fi
}

# Create process & user logdir with permissions.
create_logdir()
{
	dir_name=$1
	dircreationmode=$2
	service_user=$3
	user_not_found=0
	ISROOT=`id | egrep "^uid=0\("`

	if [ ${dryrun_req} -eq 1 ] ; then
		echo "Directory [${dir_name}] will be created with [${dircreationmode}] permissions."
	else
		if [ ! -d ${NBLOGS}/${dir_name} ] ; then
			echo "Creating [${dir_name}] with permissions [${dircreationmode}]."
			# Do not throw any error if parent directory does not exist.
			# Example : "./mklogdir user_ops/nbjlogs".
			mkdir -p ${NBLOGS}/${dir_name}

			if [ "${ISROOT}" != "" ] ; then
				get_service_user > /dev/null 2>&1
				if [ $? -eq 0 ] ; then
					if [ "${nb_service_user}" != "" ] && [ "${nb_service_user}" != "root" ] && [ ${service_user} -eq 1 ] ; then
						chown ${nb_service_user} ${NBLOGS}/${dir_name}
					fi
				fi
			fi

			# If username is not empty and the dir_name contains the user to be created, change its ownership.
			if [ "${username}" != "" ] ; then
				if echo ${dir_name} | grep "/${username}" >/dev/null ; then
		                	if [ ! -z ${group_id} ] ; then
						chown ${username}:${group_id} ${NBLOGS}/${dir_name}
					else
						chown ${username} ${NBLOGS}/${dir_name}
					fi
					# Remove user log directory if chown fails for user log.
					if [ $? -ne 0 ] ; then
						rm -rf ${NBLOGS}/${dir_name}
						echo "Directory [${dir_name}] has not been created. Please verify that the username is correct."
						user_not_found=1
					fi
				fi
			fi
		else
			echo "Directory [${dir_name}] exists.  Modifying its permission to [${dircreationmode}]."
		fi
		if [ ${user_not_found} -eq 0 ] ; then
			chmod ${dircreationmode} ${NBLOGS}/${dir_name}
		fi
	fi
}

# Fix folder permission for process_log_dir & user_log_dir and files within them.
fix_folder_and_files_permission()
{
	dir_name=$1
	dircreationmode=$2
	# Function fix_folder_and_files_permission() is always called with parent directory permissions.
	# So subdirectory permissions are not available.
	subdircreationmode=0755
	sub_dir_mode_word="drwxr-xr-x"
	# If not an EOL/critical directory, i.e. it is mklogdir default directory, and log mode is secured.
	if [ ${eol_critical_directory} -eq 0 -a ${ALLOW_WORLD_READABLE_LOGS} -eq 0 ] ; then
		subdircreationmode=0700
		sub_dir_mode_word="drwx------"
	fi
	directorywithoutuser=0
	fileexception=0
	fixperm_dir_list=""
	# Check if directory name is in user exception list.
	for ex_dir in ${user_dir_exception}
	do
		if [ "${ex_dir}" = "${dirname}" ] ; then
			subdircreationmode=0755
			sub_dir_mode_word="drwxr-xr-x"
			fileexception=1
			break
		fi
	done
	if [ -d "${NBLOGS}/${dir_name}" ] ; then
		if [ "${dircreationmode}" = "0755" ] ; then
			# Check if there exists any user directories in process dir, add all to fixperm_dir_list.
			for dirs in `find ${NBLOGS}/${dir_name} -type d`
			do
				fixperm_dir_list="${fixperm_dir_list}	${dirs}"
			done
		else
			fixperm_dir_list=${NBLOGS}/${dir_name}
			directorywithoutuser=1
		fi
		for dirs in ${fixperm_dir_list}
		do
			dir_info=`ls -ld ${dirs}`
			# Fetch the existing directory permissions.
			exist_dir_perms=`echo ${dir_info} | ${AWK} '{print $1}' | cut -c-10`
			# Remove NBLOGS path string from dirs.
			dir_name_loop=`echo ${dirs} | sed "s#${NBLOGS}/##g"`
			mode_word_local=${mode_word}
			dir_creation_mode_local=${dircreationmode}
			filescreationmode=0600
			if [ ${ALLOW_WORLD_READABLE_LOGS} -eq 1 -o ${fileexception} -eq 1 ] ; then
				filescreationmode=0644
			fi
			if [ ${directorywithoutuser} -eq 0 ] ; then
				# Compare if directory is not a parent diretory, i.e. not equal to dir_name passed to fix_folder_and_files_permission().
				if [ "$dir_name" != "$dir_name_loop" ] ; then
					mode_word_local=${sub_dir_mode_word}
					dir_creation_mode_local=${subdircreationmode}
				fi
			fi
			# Here, we will be verifying if the log folders exist with their appropriate permissions.
			# We also fix the permissions of log files if they are not appropriate.
			if [ "${mode_word_local}" != "${exist_dir_perms}" ] ; then
				echo "Will be setting permissions of "[${dir_name_loop}]" to "[${dir_creation_mode_local}]"."
				if [ ${change_file_permissions} -eq 1 ] ; then
					echo "Will be setting permissions of all files inside "[${dir_name_loop}]" to "[${filescreationmode}]"."
				fi

				if [ ${dryrun_req} -eq 1 ] ; then
					continue
				else
					chmod ${dir_creation_mode_local} ${NBLOGS}/${dir_name_loop}
					if [ $? -eq 0 ] ; then
						echo "Fixed "[${dir_name_loop}]" directory permissions."
						# Fixing file permissions. Flag 'change_file_permissions' is enabled by default.
						if [ ${change_file_permissions} -eq 1 ] ; then
							if find ${NBLOGS}/${dir_name_loop}/ -type f ! -perm ${filescreationmode} -exec chmod ${filescreationmode} '{}' + >/dev/null 2>&1; then
								echo "Fixed permissions of all files inside directory [${dir_name_loop}]."
							else
								echo "Failed to update permissions of files inside directory [${dir_name_loop}]."
							fi
						fi
					fi
				fi
			else
				echo "Directory [${dir_name_loop}] has appropriate permissions."
				# Fixing file permissions. Flag 'change_file_permissions' is enabled by default.
				if [ ${change_file_permissions} -eq 1 ] ; then
					echo "Will be setting permissions of all files inside "[${dir_name_loop}]" to "[${filescreationmode}]"."
					if [ ${dryrun_req} -eq 1 ] ; then
						continue
					fi
					if find ${NBLOGS}/${dir_name_loop}/ -type f ! -perm ${filescreationmode} -exec chmod ${filescreationmode} '{}' + >/dev/null 2>&1; then
						echo "Fixed permissions of all files inside directory [${dir_name_loop}]."
					else
						echo "Failed to update permissions of files inside directory [${dir_name_loop}]."
					fi
				fi
			fi
		done
	fi
}

# Function to process operations for all log dirs.
perform_op_all_log_dir()
{
	OP=$1
	eol_critical_directory=0
	for dir in ${logs_list}
	do
		# Parsing log list on delimiter ; and storing the output in $dirinfo.
		dirinfo=`echo ${dir} | ${AWK} -F";" '{print $1,$2,$3}'`
		set -- ${dirinfo}
		dirname=$1
		fixperm_dir=$1
		dircreationmode=$2
		parentdircreationmode=$2
		subdircreationmode=$2
		service_user=$3
		set_dir_permission_list "${dirname}" "${parentdircreationmode}"
		for dir_name in ${dirname}
		do
			dircreationmode=$parentdircreationmode
			# If username is not empty and the dir_name contains the user to be created, change its permissions.
			if [ "${username}" != "" ] ; then
				if echo ${dir_name} | grep "/${username}" >/dev/null ; then
					dircreationmode=$subdircreationmode
				fi
			fi
			case "${OP}" in
				'create')
					create_logdir "${dir_name}" "${dircreationmode}" "${service_user}"
					;;
				'list')
					echo "Directory [${dir_name}] will be created with [${dircreationmode}] permissions."
					;;
				'fixFolderPerm')
					# Store existing permissions in recoverPermissions.txt for reference by users in case of an error.
					if [ -d ${NBLOGS}/${dir_name} -a ${savePrevPermisssions_req} -eq 1 ] ; then
						find ${NBLOGS}/${dir_name} \( -type f -o -type d \) | perl -l -n -e 'printf "chmod %o \"$_\"\n", (stat $_)[2] & 07777' >> "${NBTMPDIR}/recoverPermissions.txt"
					fi
					fix_folder_and_files_permission "${fixperm_dir}" "${dircreationmode}"
					;;
			esac
		done
	done

	# Fixing permissions of files in EOL and critical directories.
	# All directories/sub-directories of EOL and critical components will have 755 permissions.
	if [ "${OP}" = "fixFolderPerm" ] ; then
		eol_critical_directory=1
		for dir_name in ${eol_and_critical_dir_list}
		do
			if [ -d "${NBLOGS}/${dir_name}" ] ; then
				# Store existing permissions in recoverPermissions.txt for reference by users in case of an error.
				if [ ${savePrevPermisssions_req} -eq 1 ] ; then
					find ${NBLOGS}/${dir_name} \( -type f -o -type d \) | perl -l -n -e 'printf "chmod %o \"$_\"\n", (stat $_)[2] & 07777' >> "${NBTMPDIR}/recoverPermissions.txt"
				fi

				# Pass dircreationmode as 0755 so that all sub-directories are captured in fix_folder_and_files_permission.
				dircreationmode=0755
				mode_word="drwxr-xr-x"
				fix_folder_and_files_permission "${dir_name}" "${dircreationmode}"
			fi
		done
	fi
}

perform_op_log_dir()
{
	OP=$1
	logdir=$2
	eol_critical_directory=0
	for dir in ${logs_list}
	do
		dirinfo=`echo ${dir} | ${AWK} -F";" '{print $1,$2,$3}'`
		set -- ${dirinfo}
		dirname=$1
		fixperm_dir=$1
		service_user=$3
		if [ "${dirname}" = "${logdir}" ] ; then
			# Log directory specified is a valid NetBackup log directory.
			if [ "${OP}" = "find" ] ; then
				found=1
				return
			fi
			dircreationmode=$2
			parentdircreationmode=$2
			subdircreationmode=$2
			set_dir_permission_list "${dirname}" "${parentdircreationmode}"
			for dir_name in ${dirname}
			do
				dircreationmode=$parentdircreationmode
				# If username is not empty and the dir_name contains the user to be created, change its permissions.
				if [ "${username}" != "" ] ; then
					if echo ${dir_name} | grep "/${username}" >/dev/null ; then
						dircreationmode=$subdircreationmode
					fi
				fi
				case "${OP}" in
					'create')
						create_logdir "${dir_name}" "${dircreationmode}" "${service_user}"
						;;
					'display')
						echo "Directory [${dir_name}] will be created with [${dircreationmode}] permissions."
						;;
					'fixFolderPerm')
						dir_name=${dirname}
						fix_folder_and_files_permission "${fixperm_dir}" "${dircreationmode}"
						;;
				esac
			done
			break
		fi
	done

	# Fixing permissions of files in EOL and critical directories.
	# All directories/sub-directories of EOL and critical components will have 755 permissions.
	# Don't compare OP variable here. It can lead to creation of EOL/critical directory with mklogdir.
	if [ ${fixFolderPerm_req} -eq 1 ] ; then
		for dir_name in ${eol_and_critical_dir_list}
		do
			if [ "${dir_name}" = "${logdir}" ] ; then
				eol_critical_directory=1
				# Log directory specified is a valid EOL'd/critical NetBackup log directory.
				if [ "${OP}" = "find" ] ; then
					found=1
					return
				fi
				if [ -d "${NBLOGS}/${dir_name}" ] ; then
					# Pass dircreationmode as 0755 so that all sub-directories are captured in fix_folder_and_files_permission.
					dircreationmode=0755
					mode_word="drwxr-xr-x"
					fix_folder_and_files_permission "${dir_name}" "${dircreationmode}"
				fi
				break
			fi
		done
	fi
}

create_req=0
dryrun_req=0
fixFolderPerm_req=0
list_req=0
user_req=0
user_def=0
allowWW_req=0
n=0
OPENVDIR="/usr/openv"
NBDIR="${OPENVDIR}/netbackup"
NBTMPDIR="${OPENVDIR}/tmp"
NBLOGS="${NBDIR}/logs"
NBBIN="${NBDIR}/bin"
revert_permissions=0
savePrevPermisssions_req=0

# Variable change_file_permissions is enabled by default.
# If we want to skip the modification of file permissions, we can set its value to 0 and merge.
change_file_permissions=1

# Read value of bp.conf entry ALLOW_WORLD_READABLE_LOGS.
allow_world_readable_logs

if [ "$1" != "" ] ; then
	for ARG in $*
	do
		valid=0
		cmd=`echo "${ARG}" | ${AWK} -F"-" '{print $2}'`
		validate_command "${cmd}"
		case "${ARG}" in
			'-create')
				create_req=1
				;;
			'-dryrun')
				dryrun_req=1
				;;
			'-list')
				list_req=1
				;;
			'-fixFolderPerm')
				fixFolderPerm_req=1
				;;
			'-user')
				user_req=1
				user_def=1
				username=`echo $* | sed -n 's/^.*\-user/user/p' | ${AWK} -F" " '{print $2}'`
				;;
			'-allowWW')
				allowWW_req=1
				;;
			'-savePrevPermissions')
				# Internal option called along with -fixFolderPerm option from updrade script.
				savePrevPermisssions_req=1
				;;
			'-revertPermissions')
				revert_permissions=1
				;;
			*)
				if [ ${user_def} -eq 1 ] ; then
					user_def=0
					continue
				elif [ ${savePrevPermisssions_req} -eq 1 ] ; then
					continue
				else
					# Adding log directories passed by commandline.
					eval dir_list${n}="${ARG}"
					n=`expr $n + 1`
				fi
				;;
		esac
	done
else
	# Retaining the existing behaviour of mklogdir; if no command line parameter is specified, create all the log directories.
	perform_op_all_log_dir "create"
	exit
fi

# If only -allowWW option is specified.
if [ $# -eq 1 -a ${allowWW_req} -eq 1 ] ; then
	perform_op_all_log_dir "create"
	exit
fi

# If -revertPermissions is specified.
if [ ${revert_permissions} -eq 1 ]; then
	if [ -f "${NBTMPDIR}/recoverPermissions.txt" ] ; then
		echo "Recovery file available. Reverting the permissions to previous version."
		. "${NBTMPDIR}/recoverPermissions.txt"
	else
		echo "Recovery file does not exist."
	fi
	exit
fi

# Cannot specify create and fixFolderPerm together.
if [ ${create_req} -eq 1 ] ; then
	if [ ${fixFolderPerm_req} -eq 1 ] ; then
		echo "Invalid usage!"
		print_usage_and_exit
	fi
fi

# Cannot specify any other options with list.
if [ ${list_req} -eq 1 ] ; then
	if [ ${create_req} -eq 1 -o \
		${fixFolderPerm_req} -eq 1 -o \
		${dryrun_req} -eq 1 -o \
		${user_req} -eq 1 ] ; then
		echo "Invalid usage!"
		print_usage_and_exit
	else
		perform_op_all_log_dir "list"
	fi
fi

# Cannot specify fixFolderPerm and user together.
if [ ${fixFolderPerm_req} -eq 1 -a ${user_req} -eq 1 ] ; then
	echo "Invalid usage!"
	print_usage_and_exit
fi

if [ ${allowWW_req} -eq 0 ] ; then
	# If username is not specified.
	if [ ${user_req} -eq 1 -a "${username}" = "" ] ; then
		echo "Invalid usage!"
		print_usage_and_exit
	fi
	# If only username is specified, create the log directories.
	if [ "${dir_list0}" = "" -a ${user_req} -eq 1 ] ; then
		perform_op_all_log_dir "create"
		exit
	fi
else
	# cannot specify allowWW with username
	if [ ${user_req} -eq 1 ] ; then
		echo "Invalid usage. Cannot specify allowWW with username."
		print_usage_and_exit
	fi
fi

# If only dryrun option is specified, show list & exit.
if [ ${dryrun_req} -eq 1 ] ; then
	if [ ${create_req} -eq 0 -a ${fixFolderPerm_req} -eq 0 -a "${dir_list0}" = "" ] ; then
		perform_op_all_log_dir "list"
		exit
	fi
fi

# If user specifies log dirs, process each of them in a loop.
i=0

if [ ${n} -gt 0 ] ; then
	while [ ${i} -lt ${n} ] ;
	do
		found=0
		# Fetch the directory name from the array.
		eval logdir=""\$dir_list${i}""
		perform_op_log_dir "find" "${logdir}"
		if [ ${found} -eq 1 ] ; then
			process_request "${logdir}"
		else
			echo
			echo "Directory [${logdir}] requested for creation is not a valid NetBackup debug directory.  Please try again."
		fi
		i=`expr $i + 1`
	done
else
	# No log directories specified in command line, going ahead and processing all.
	process_request "all"
fi
