#!/bin/ksh93
#  ALTRAN_PROLOG_BEGIN_TAG                                                    
#  This is an automatically generated prolog.                                  
#                                                                              
#  Copyright (C) Altran ACT S.A.S. 2019,2020,2021.  All rights reserved.  
#                                                                              
#  ALTRAN_PROLOG_END_TAG                                                      
#                                                                              
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# 61haes_r714 src/43haes/usr/sbin/cluster/cspoc/utilities/smitlvm.sh 1.7.5.1 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 1996,2013 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
#
# @(#)  7b36ae1 43haes/usr/sbin/cluster/cspoc/utilities/smitlvm.sh, 726, 2147A_aha726, Sep 08 2021 09:17 PM
#
#############################################################
#          =  smitlvm.sh = 
# Wrapper for SMIT to handle -cspoc flag.  This script is 
#  called multiple times from SMIT to fill in dialogs and also
#  to handle quoting problems related to the -cspoc "***" flag.
#
#  This also contains chfsawk which is an edited version of lsjfs,
#	a standard AIX tool that takes the output of cl_lsfs and 
#	changes it into colon delimited format.
#
#     
#   $1 = '-1' cl_chlv
#        '-2' cl_chfs
#        '-3' (namehdr for chlv)
#	 '-4' (namehdr for chfs)
#	 '-5' (namehdr) returns RGNAME:NAME
#	 '-6' cl_lslv
#	 '-7' cl_chlv dialog 
#	 '-8' cl_rmlv 
#	 '-9' cl_rmfs
#	 '-10' cl_chfs
#        '-11' cl_lspvsmit
#        '-12' cl_extendvg
#        '-13' cl_reducevg
#        '-14' cl_importvg
#        '-15' cl_mirrorvg
#        '-16' cl_unmirrorvg
#        '-17' cl_mklv
#        '-18' cl_extendlv
#        '-19' cl_mklvcopy
#        '-20' cl_rmlvcopy
#        '-21' cl_syncvg
#        '-22' (namehdr for disks) returns NODE:HDISK NAMES
#   
#############################################################

######################################################################
#       chfsawk () 
#
#       This awk script is used to parse the output of cl_lsfs -qc and 
#       put it in a format acceptable to SMIT.
#
#       The cl_lsfs -qc output is:
#       #MountPoint:Device:Vfs:Nodename:Type:Size:Options:AutoMount:Acct
#       /:/dev/hd4:jfs::bootfs:8192:rw:yes:no
#         (lv size 8192:fs size 8192:frag size 4096:nbpi 4096:compress no)
#
#       It needs to be translated into:
#       #MountPoint:Device:Vfs:Nodename:Type:Size:Options:AutoMount:Acct:\
#               OtherOptions:LvSize:FsSize:FragSize:Nbpi:Compress:
#       /:/dev/hd4:jfs::bootfs:8192:rw:yes:no::8192:8192:4096:4096:no:
#
######################################################################

function chfsawk
{

	if ! RESULT=$(cl_lsfs -cspoc "-g $1" -cq $2)
	then
	    #if cl_lsfs did not successfully complete, exit and return to SMIT
	    print $RESULT
	    exit 1
	fi

#first strip the nodename(and spaces) off of the cl_lsfs output

cl_lsfs -cspoc "-g $1" -cq $2 | cut -d":" -f2-1000 | cut -d" " -f2-1000 | awk -F: '
BEGIN {
                #
                # If the query from lsfs -q fails then then there
                # will be no parenthetical list. The query_good
                # flag will be set any time the parenthetical list
                # is encountered.
                #
        query_good = 0
}

        #
        # Match the first line; it begins w/ "#"
        #
NR == 1 && $1 ~ /\#.+/ {
                #
                # Print out the lsjfs header
                #
        printf ("%s%s\n", $0, \
                ":OtherOptions:LvSize:FsSize:FragSize:Nbpi:Compress:");
        continue;
}
        #
        # Look at JFS only
        #       
NR >  1 && $3 == "jfs" {

        if (NR > 2)
        {
                if (query_good)
                {
                        printf ("\n")
                        query_good = 0 
                }
                else
                        printf (":::::\n")
        } 

                #
                # Print first 6 fields
                # MountPoint:Device:Vfs:Nodename:Type:Size
                #
        for (i = 1; i < 7; ++i)
                printf ("%s:", $i);
                #
                # Pull nodev and nosuid out of 7th field if present;
                # these will be printed under OtherOptions; this
                # is a smit requirement.
                #
        sep = ""
        other["nodev"] = ""
        other["nosuid"] = ""

        n = split($7, options, ",");
        for (i = 1; i <= n; ++i)
        {
                if (options[i] == "nodev" || options[i] == "nosuid")
                            other[options[i]] = 1;
                else 
                {
                        printf ("%s%s", sep, options[i]);
                        sep = ","
                }
        }
        
        for (i = 8; i <= NF; ++i)
                printf (":%s", $i);
                
        if (other["nodev"] && other["nosuid"])
                printf (":nodev,nosuid:");
        else if (other["nodev"])
                printf (":nodev:");
        else if (other["nosuid"])
                printf (":nosuid:");
        else 
                printf ("::");

        continue

} 
        #
        # Process the filesystem geometry numbers (size, frag, nbpi, compress)
        #
NR > 1 && $1 ~ /[" "\t]*\(.+[0-9]+/ {

        gsub (/[\(\)]/, "");
        #
        # pick out each value out of the parenthetical list. 
        #
        num_fields = split ($0, fields, ":")
        for (i = 1; i <= num_fields; i++)
        {
                num_values = split (fields[i], values, " ");
                printf ("%s:", values[num_values]);
        }
        query_good = 1
}
        
END {
        if (query_good)
                printf ("\n")
        else
                printf (":::::\n")
}'
}

#
# Main Starts Here
#
[[ $VERBOSE_LOGGING == high ]] && set -x
[[ $VERBOSE_LOGGING == high ]] && version='1.7.5.1 $Source: 61haes_r711 43haes/usr/sbin/cluster/cspoc/utilities/smitlvm.sh 1$'

PROGNAME=${0##*/}
PATH="$(/usr/es/sbin/cluster/utilities/cl_get_path all)"

# Make sure that all scripts know that they were called from SMIT.
export _CSPOC_CALLED_FROM_SMIT="true"

COMMAND=$1
RGNAME=$2

case $COMMAND in
-1)
	shift 2
	cl_chlv -cspoc "-g $RGNAME" "$@"
	exit $?
	;;
-2)
	shift 2
	cl_chfs -cspoc "-g $RGNAME" $*
	exit $?
	;;
-3)     shift 1
	jdcls () {
        NAME=$2
 	RGNAME=$1
	if ! RESULT=$(cl_lslvsmit -cspoc "-g $RGNAME" $NAME)
	then
	    ## Check to see if cl_lslvsmit failed and if so report it to SMIT
	    print $RESULT
	    exit 1
	fi

	echo $RESULT | sed 's/^.*: //' ; }; jdcls $1
	;; 
-4)	shift 1
	jdchfs () {
	RGNAME=$1
	NAME=$2
	MNAME=$(echo $NAME |sed 's/\//\\&/g')
	if ! R=$(chfsawk $RGNAME $NAME)
	then	
	    print $R
	    exit 1
	fi

	chfsawk $RGNAME $NAME | sed 's/#MountPoint/#RGName:FSName:MountPoint/' | sed "s/$MNAME/$RGNAME:$MNAME:$MNAME/1"
	}; jdchfs $1 $2
	;;	
-5)     shift 1
 	jdlv () {
		NAME=$2
		RGNAME=$1
 		echo $RGNAME:$NAME
	} ; jdlv $1
 	;;
-6)	RGNAME=$2
	NAME=$3
	shift 3
	cl_lslv -cspoc "-g $RGNAME" $* $NAME
	;;
-7)	#
	:   This extracts inforamation about logical volume $2
	:   in a format suitable for a command_to_classify for 
	:   a SMIT panel
	#
	shift 1
	jdlv2 () {
		#
		:   This is copied from the corresponding logic
		:   in the name header for the SMIT panel for the
		:   base chlv command.
		#
		RGNAME=$1
		NAME=$2
		if ! LVID=$(getlvodm -l $NAME); 
		then
		  exit 1
		fi
		Q1=$(getlvodm -c $LVID | cut -f2-6,8 -d' ' | sed '1s/ /:/g');
		Q4=$(getlvodm -B $LVID); 
		Q2=$(lquerylv -L $LVID -nMPRv); 
		Q3=$(echo $Q2 | sed '1s/ /:/g'); 
		Q5=$(lquerylv -L $LVID -w); 
		Q6=$(lquerylv -L $LVID -I); 
		LC_ALL=C lquerylv -L $LVID -E | read MP1 MP2 MP3
		lvm_encrypt=$(LC_ALL=C lslv $LVID | grep -w ENCRYPTION | awk '{print $2}')
                if [[ -z $lvm_encrypt ]];then
                    lvm_encrypt="no"
                fi
		echo $RGNAME:$NAME:$Q1:$Q4:$Q3:$Q5:$Q6:$MP1:$MP2:$MP3:$lvm_encrypt;
	}; jdlv2 "$1" $2
	;;
-8)     RGNAME=$2
        NAME=$3
        shift 3
        cl_rmlv -cspoc "-g $RGNAME" $* $NAME
        ;;
-9)	#
	:   Format is
	:   smitlvm -10 "resource group" "file system" other operands...
	#
	RG_name=$2
	FS_name=$3
	shift 3		# gets rid of the '-9', resource group and file system
	if [[ $* != @(*-cspoc -n*) ]]
	then
	    #
	    :	If no explicit node list given, use resource group
	    #
	    cl_rmfs -cspoc "-g $RGNAME" $* $FS_name
	else
	    #
	    :	Else stick with explicit node list
	    #
	    cl_rmfs $* $FS_name
	fi
	;;
-10)	#
	:   Format is
	:   smitlvm -10 "-cspoc" "-n<node list>" other operands
	:   It is assumed to be well formed for passing to cl_chfs...
	#
	shift 		# gets rid of the '-10'
	# Code to handle ''(space character) as valid value for -u flag
	for option in $*
	do
		option_string="$option_string $option"
		shift
		if [[ $option == "-u" ]]
		then
			operand=$1
			if [[ -z "$operand" || "$operand" == @(-*) || "$operand" == @(/*) ]]
			then
				option_string="$option_string ''"
			fi
		fi
	done
	cl_chfs $option_string $FS_name
	;;
-11)    RGNAME=$2
	shift 2
	cl_lspvsmit -cspoc "-g $RGNAME" $*
	;;
-12)    RGNAME=$2
	shift 2
	cl_extendvg -cspoc "-g $RGNAME" $*
	;;
-13)    RGNAME=$2
	shift 2
	cl_reducevg -cspoc "-g $RGNAME" $*
	;;
-14)	RGNAME=$2
	shift 2
	cl_importvg -cspoc "-g $RGNAME" $*
	;;
-15)	RGNAME=$2
	shift 2
	cl_mirrorvg -cspoc "-g $RGNAME" $*
	;;
-16)	RGNAME=$2
	shift 2
	cl_unmirrorvg -cspoc "-g $RGNAME" $*
	;;
-17)	RGNAME=$2
	shift 2
	cl_mklv -cspoc "-g $RGNAME" "$@"
	;;
-18)	RGNAME=$2
	shift 2
	cl_extendlv -cspoc "-g $RGNAME" $*
	;;
-19)	RGNAME=$2
	shift 2
	cl_mklvcopy -cspoc "-g $RGNAME" $*
	;;
-20)	RGNAME=$2
	shift 2
	cl_rmlvcopy -cspoc "-g $RGNAME" $*
	;;
-21)	TYPE_FLAG=$2
	RGNAME=$3
	VGLVNAME=$4
	shift 4
	cl_syncvg -cspoc "-f -g $RGNAME" $* $TYPE_FLAG $VGLVNAME
	;;
-22)	shift
	NODE=$1
	COMPSTR=$(dspmsg -s 5 cspoc.cat 40 "Auto-select")
	[[ "$NODE" == "$COMPSTR" ]] && {
	    print " : "
	    exit 0
	}
	# There is a tab and a space between the brackets here.
	NODE=${NODE%%[ 	]*}
	DISKS=$(print -- $1 | sed -e "s/$NODE //g")
	#
	# If configuration has a site defined and Cross-Site LVM Mirroring
	# is configured remove site names from disk list.
	#
	SITES=$(odmget HACMPsite | \
	awk '
	{
	   gsub(/"/,"")
	   if ($1 == "name")
	   {
	      printf("%s ",$3)
	   }
	}')
	if [[ -n $SITES ]]
	then
	   for SITE in $SITES
	   do
	      DISKS=$(print $DISKS | sed -e "s/$SITE//g")
	   done
	fi
	echo "$NODE:$DISKS"
	;;

-whichlv ) 
	#
	:   Present the pick list of possible logical volumes to hold the file system
	#
	FS_type=$2
	VG_name=$3
	Nodelist=$4

	#
	: Check if RBAC is enabled
	#
  typeset is_rbac_enabled=""
  is_rbac_enabled=$(clodmget -nq "group=LDAPClient and name=RBACConfig" -f value HACMPLDAP 2>/dev/null)

	#
	:  For a non root user, append the user name to the output file.
	#
	[[ -z "$LOGIN" ]] && user_name=$(id -nu 2>/dev/null) || user_name="$LOGIN"
	if [[ $user_name != "root" && $is_rbac_enabled == "YES" ]];then
	  CL_DATFILE="/var/hacmp/tmp/choclv.out"_$user_name
	else
	  CL_DATFILE="/var/hacmp/tmp/choclv.out"
	fi
  
	if [[ ! -s $CL_DATFILE ]] || ! grep -qx "${VG_name}:" $CL_DATFILE
	then
	    #
	    :	If the cache file does not contain the information expected,
	    :	rebuild it
	    #
	    /usr/es/sbin/cluster/sbin/cl_lsvg -cspoc -n${Nodelist} -l $VG_name > $CL_DATFILE
	    #
	    : Change the ownership of output file, for a non root user.
	    #
	    [[ $user_name != "root" ]] && chown $user_name $CL_DATFILE
	fi

	#
	:	Select logical volumes of this type
	#
	if [[ $FS_type == 'E' ]]
	then
	    lookfor='jfs2'
	else
	    lookfor='jfs'
	fi
	
	header_msg1=$(dspmsg -s 101 cspoc.cat 84 "To Add a new File System to volume group %s," $VG_name)
	header_msg2=$(dspmsg -s 101 cspoc.cat 85 "you must either chose to")
	create_new_msg=$(dspmsg -s 101 cspoc.cat 86 "Create a new Logical Volume for this File System")
	chose_existing_msg=$(dspmsg -s 101 cspoc.cat 87 "Or select an existing logical volume from the list below")
	
	#
	:	Display the possible logical volumes, along with a "create a new one" message
	#
	cat $CL_DATFILE | \
	awk 'NR == 1 { print "# '"${header_msg1}"'"
		       print "# '"${header_msg2}"'"
		       print " "
		       print "  '"${create_new_msg}"'"
		       print " "
		       print "# '"${chose_existing_msg}"'" }
	     NR == 2 { print "#" $0 }
	     NR >= 3 { if (($2 == "'${lookfor}'" ) && ($7 !~ "^/")) print " " $0}'
	;;

	
*)	echo 'BAD ARG TO cl_smitlvm'
	exit 1
	;;
esac
