#!/bin/sh
#
# ###################################################################
# Copyright (c) 2011-2019, Dell Inc. or its subsidiaries. All Rights Reserved.
#
# This file is a part of Dell EMC PowerPath management service.
#
# description: Interactive editor for the emcp_mond configuration file.
#
# ###################################################################

PATH=/usr/bin:/bin:/usr/sbin/:/sbin; export PATH
: ${TMPDIR:=/tmp}

if [ -z "$CONF_EDIT_RESTART" ]
then
    case `uname` in
        Linux)
            cmd=`which $0`
            CONF_EDIT_RESTART=bash
            export CONF_EDIT_RESTART
            exec /bin/bash $cmd $*
            ;;
        SunOS|AIX|HP-UX)
            cmd=`which $0`
            CONF_EDIT_RESTART=ksh
            export CONF_EDIT_RESTART
            exec /usr/bin/ksh $cmd $*
            ;;
    esac
fi

SNMP_OK=T  ##Unset in "case" below to disable SNMP param edits.
ID=/usr/bin/id
TR=/usr/bin/tr

case `uname` in
    Linux)
        SYSTEMD_SUPPORT=no
        sles_version=0
        oracle_version=0
        rhel_version=0
        if [ -f /etc/os-release ]; then
            host_id=`cat /etc/os-release | grep "^ID=" | awk -F'"' '{print $2}'`
            if [ "${host_id}" == "sles" ]; then
                sles_version=`cat /etc/os-release | grep "^VERSION_ID=" \
                    | awk -F'"' '{print $2}' | sed -e 's/\([0-9]*\)\..*/\1/'`
            fi
        fi
        if [ -f /etc/oracle-release ]; then
            if [ $(uname -r | grep -c uek) -ne 0 ]
            then
                oracle_version=`sed '/^[ \t]*#/d;s/^.*release \([0-9]\)[0-9.]*.*/\1/' \
                                             /etc/oracle-release`
            fi
        elif [ -f /etc/redhat-release ]; then
            rhel_version=`sed '/^[ \t]*#/d;s/^.*release \([0-9]\)[0-9.]* .*/\1/' \
                                        /etc/redhat-release`
        fi

        if [ "${rhel_version}" -ge "7" ] || [ "${oracle_version}" -ge "7" ] || [ "${sles_version}" -ge "12" ]; then
            SYSTEMD_SUPPORT=yes
        fi

        shopt -s extglob
        set -T
        platf_conf_dir=/etc/opt/emcpower
        platf_conf_sample=${platf_conf_dir}/emcp_mond-sample.conf
        if [ "$SYSTEMD_SUPPORT" == "yes" ]; then
            platf_restart='restart_daemon_linux_systemd_support'
        else
            platf_restart='restart_daemon /etc/init.d/emcp_mond.sh'
        fi
        ;;
    SunOS)
        case `uname -r` in
          5.10)
            BASEDIR=`pkginfo -r EMCpower 2>/dev/null` ;;
          5.11)
            BASEDIR=`pkg search -Hl -o search.match \
                                    '*/EMCpower:set:pkg.basedir:*'` ;;
        esac
        platf_conf_dir=/etc/emc
        conf_sample_dir=${BASEDIR:=/opt}/EMCpower/scripts
        platf_conf_sample=${conf_sample_dir}/emcp_mond.conf
        platf_restart='sol_restart_daemon'
        ID=/usr/xpg4/bin/id
        TR=/usr/xpg4/bin/tr
        ;;
    HP-UX)
        SNMP_OK=''
        platf_conf_dir=/etc/emc
        platf_conf_sample=${platf_conf_dir}/emcp_mond-sample.conf
        platf_restart='restart_daemon /sbin/init.d/emcpmond'
        ;;
     AIX)
        platf_conf_dir=/etc/emc
        platf_conf_sample=${platf_conf_dir}/emcp_mond.conf
        platf_restart='restart_daemon /etc/rc.emcp_mond'
        ;;
esac


: ${CONF_DIR:=$platf_conf_dir}
: ${CONF_FILE:=emcp_mond.conf}
: ${CONF_SAMPLE:=$platf_conf_sample}
: ${RESTART:=$platf_restart}

##--------------------------- error messages ---------------------------

##------------------------- Interactive prompts ------------------------
PATH_DEAD_NAME="Path Dead"
PATH_LIVE_NAME="Path Alive"
ALL_PATH_DEAD_NAME="All Paths Dead"
NT_ALL_PATH_DEAD_NAME="Not All Paths Dead"
VOL_DEAD_NAME="Volume Dead"
PATH_LATENCY_NAME="Maximum Path Latency Exceeded"
##--------------------------- Help messages ----------------------------
EVENT_MENU_HELP=\
'Enter 1 to enable a disabled event or disable an enabled event.
Enter 2 to change the delay between event and SNMP trap generation.
Enter 3 to return to the top level menu.
Enter q to exit this program.
Enter ? to display this message.'
TOP_MENU_HELP=\
'Enter the number at the beginning of each line to select an action.
Enter q to exit this program.  Before the program ends you will have
an opportunity to save configuration changes.
Enter ? to display this message.'
DELAY_TIME_HELP=\
'Enter a value for the number of seconds to wait between the occurrence
of an event and the generation of an SNMP trap.  If you press "enter"
without entering a value, the current value will be retained.'
HEARTBEAT_TIME_HELP=\
'Enter a value for the maximum number of minutes between messages sent
to the management console.  The new value must be in the range 1 to 60,
inclusive. The default value is 10.  If you press "enter" without
entering a value, the current value will be retained.'
PORT_HELP=\
'Enter a value for the port used to communicate with the remote management
station.
The new value must be in the range 49152 to 65535, inclusive, or 9083.
The default value is 9083.  If you press "enter" without entering a value,
the current value will be retained.'
EXIT_MENU_HELP=\
'Enter 1 to save all changes made to the emcp_mond configuration file in
this edit session and restart emcp_mond before exiting.
Enter 2 to save all changes made to the emcp_mond configuration file in
this edit session before exiting.  Emcp_mond will not be restarted.
Enter 3 to immediately exit the program.  Any changes made after the last
write to the configuration file will be lost. Emcp_mond will not be restarted.
Enter 4 to return to the top level menu.
Enter q to exit this program after saving changes to the emcp_mond
configuration file.
Enter ? to display this message.'
##----------------------------------------------------------------------

STATE[0]="Disabled"
STATE[1]="Enabled"

##-------------------------- Display helpers --------------------------
display_error()
{
    printf "Error: "
    display_message "$*"
    return 1
}

display_fatal_error()
{
    display_error "$*"
    exit 1
}

display_warning()
{
    printf "Warning: "
    display_message "$*"
}

display_message()
{
    printf "$*"
    echo
    echo
}

display_help()
{
    if [ "$1" ]
    then
        echo
        printf "$*"
        echo
    else
        printf 'Help is not available'
        echo
    fi
    echo
    printf 'Press "enter" to continue.'
    read
    echo
}

##------------------------ Semantic validators ------------------------
validate_heartbeat()
{
    if [ "$1" -le 60 -a "$1" -gt 0 ]
    then
        return 0  ## valid heartbeat
    else
        display_error "Heartbeat out of range: $1"
        return 1
    fi
}

validate_port()
{
    if [ "$1" -eq 9083 ]
    then
        return 0  ## valid port
    elif [ "$1" -ge 49152 -a "$1" -le 65535 ]
    then
        return 0  ## valid port
    else
        display_error "Port out of range: $1"
        return 1
    fi
}

validate_delay()
{
    if [ "$1" -lt 3600 ]
    then
        return 0  ## valid delay
    else
        display_error "Delay value out of range: $1"
        return 1
    fi
}

##--------------------------- Menu display ---------------------------

MGMTSVC_PRMPT='Change remote management service status'
HBT_PRMPT='Change management service heartbeat interval'
PORT_PRMPT='Change management service port'
SINGLEPATHGK_PRMPT='Single path gatekeeper devices'
SNMPSVC_PRMPT='Change SNMP trap generation status'
PATH_DEAD_PRMPT='Change "Path Dead" event'
PATH_LIVE_PRMPT='Change "Path Alive"  event'
ALL_PATH_DEAD_PRMPT='Change "All Paths Dead" event'
NT_ALL_PATH_DEAD_PRMPT='Change "Not All Paths Dead" event'
VOL_DEAD_PRMPT='Change "Volume Dead" event'
PATH_LATENCY_PRMPT='Change "Max. Path Latency Exceeded" event'
START_PRMPT='Save configuration file, restart daemon and exit'
SAVE_PRMPT='Write configuration file'
EXIT_SAVE_PRMPT='Save configuration file and exit'
EXIT_NOSAVE_PRMPT='Exit without saving configuration file'
EXIT_PRMPT='Exit'
UP_PRMPT='Back'
EVENT_PRMPT='Change event status'
DELAY_PRMPT='Change delay time'

#-----------------------------------------------------------------------
# get_svc_value() - Calculate the status of a service from its tag name.
# Args:
#  $1 - Name of the service.  Used to derive service parameters.
#  $2 - Name of variable to be assigned the value.
#-----------------------------------------------------------------------
get_svc_value()
{
    eval "typeset status=\$$1"
    eval "$2=${STATE[$status]}"
}

#-----------------------------------------------------------------------
# get_gtk_value() - Display the single-path-gatekeeper menu line.
# Args:
#  $1 - Name of the selection.  Used to derive parameters.
#  $2 - Name of variable to be assigned the value.
#-----------------------------------------------------------------------
get_gtk_value()
{
    typeset allow
    allow[0]="Warn"
    allow[1]="Allow"
    eval "typeset status=\$$1"
    eval "$2=${allow[$status]}"
}

#-----------------------------------------------------------------------
# get_param_value() - Display the menu line for a numeric
# parameter, like heartbeat or port number.
# Args:
#  $1 - Name of the selection.  Used to derive parameters.
#  $2 - Name of variable to be assigned the value.
#  $3 - Units of value.  (Optional.)
#-----------------------------------------------------------------------
get_param_value()
{
    eval "typeset value=\$$1"
    eval "$2=\"$value $3\""
}

#-----------------------------------------------------------------------
# get_event_value() - Display the menu line for an event.
# Args:
#  $1 - Name of the event.  Used to derive parameters.
#  $2 - Variable to receive event status
#  $3 - Variable to receive delay time
#-----------------------------------------------------------------------
get_event_value()
{
    eval "typeset status=\$$1"
    eval "$2=\"${STATE[$status]}\""
    eval "$3=\"delay \${$1[1]} sec\""
}

#-----------------------------------------------------------------------
# display_menu_line() - Display a menu line in an event submenu.
# Args:
#  $1 - Menu id string.
#  $2 - Name of the selection.  Used to derive prompt string.
#  $3 - The current value (Optional)
#-----------------------------------------------------------------------
display_menu_line()
{
    eval "typeset prompt=\${$2_PRMPT}"

    if [ "$3" ]
    then
        printf "$Format" "${Item} " "$prompt" "$3"
    else
        printf "$Format" "${Item} " "$prompt"
    fi
    eval "$1[$Item]=$2"
    Item=$(($Item+1))
}

#-----------------------------------------------------------------------
# display_top_menu() - Display the top level menu
# Args:
#  $1 - Menu id string.
#-----------------------------------------------------------------------
display_top_menu()
{
    typeset Format="%3s %-48s%-16s\n"
    typeset Item=1

    echo
    printf "$Format" " " "Item" "Value"
    printf "$Format" " " "====" "====="

    get_svc_value MGMTSVC svc_value
    display_menu_line $1 MGMTSVC "$svc_value"
    get_param_value HBT param_value minutes
    display_menu_line $1 HBT "$param_value"
    get_param_value PORT param_value
    display_menu_line $1 PORT "$param_value"
    get_gtk_value SINGLEPATHGK param_value
    display_menu_line $1 SINGLEPATHGK "$param_value"
    if [ "$SNMP_OK" ]
    then
        get_svc_value SNMPSVC svc_value
        display_menu_line $1 SNMPSVC "$svc_value"
        get_event_value PATH_DEAD event_status timeout
        display_menu_line $1 PATH_DEAD "$event_status, $timeout"
        get_event_value PATH_LIVE event_status timeout
        display_menu_line $1 PATH_LIVE "$event_status, $timeout"
        get_event_value ALL_PATH_DEAD event_status timeout
        display_menu_line $1 ALL_PATH_DEAD "$event_status, $timeout"
        get_event_value NT_ALL_PATH_DEAD event_status timeout
        display_menu_line $1 NT_ALL_PATH_DEAD \
                                        "$event_status, $timeout"
        get_event_value VOL_DEAD event_status timeout
        display_menu_line $1 VOL_DEAD "$event_status, $timeout"
        get_event_value PATH_LATENCY event_status timeout
        display_menu_line $1 PATH_LATENCY "$event_status, $timeout"
    fi
    display_menu_line $1 SAVE ""
    display_menu_line $1 EXIT ""
    echo
}
#-----------------------------------------------------------------------
# get_menu_choice() - Read the users selection and assign it to the
# global variable CHOICE.
# Args:
#  $1 - Menu id string.
#  $2 - If non-null, the default menu selection (zero-based)
#-----------------------------------------------------------------------
get_menu_choice()
{
    typeset select
    typeset choice
    typeset default

    if [ "$2" ]
    then
        default=$2
    else
        default=nn
    fi
    while true
    do
        printf "Enter number of desired choice [$default, q, ?]: "
        read select
        case "$select" in
            \?) CHOICE=HELP; break ;;
             q) CHOICE=QUIT; break ;;
            [0-9]|1[0-9])
                eval "choice=\${$1[$select]}"
                if [ "$choice" ]
                then
                    CHOICE=$choice
                    break
                else
                    display_error 'Invalid selection: $select'
                fi
                ;;
           '')  if [ "$2" ]
                then
                    eval "CHOICE=\${$1[$2]}"
                    break
                fi
                ;;
            *) display_error 'Invalid selection: $select' ;;
        esac
        echo
    done
}

#-----------------------------------------------------------------------
# display_event_menu() - Display event parameters in a submenu.
# Args:
#  $1 - Menu id string.
#  $2 - Event name.
#-----------------------------------------------------------------------
display_event_menu()
{
    typeset Format="%3s %-48s%-16s\n"
    typeset Item=1
    eval "typeset event_name=\$${2}_NAME"
    eval "typeset status=\$${2}"
    eval "typeset delay=\${${2}[1]}"

    printf "$Format" " " "Item ($event_name)" "Value"
    printf "$Format" " " "====" "====="

    display_menu_line $1 EVENT "${STATE[$status]}"
    display_menu_line $1 DELAY "$delay seconds"
    display_menu_line $1 UP ""
    echo
}

#-----------------------------------------------------------------------
# event_menu() - Display event menu, get the users menu selection,
# and preform the appropriate action.
# Args:
#  $1 - Event name
#-----------------------------------------------------------------------
event_menu()
{
    typeset MENUTAG
    typeset CHOICE

    while true
    do
        CHOICE=''
        display_event_menu MENUTAG $1
        get_menu_choice MENUTAG 3
        case "$CHOICE" in
            EVENT) eval "$1=\${FLIP[\$$1]}" ;;
            DELAY) get_delay $1 ;;
            HELP) display_help "$EVENT_MENU_HELP" ;;
            UP) break ;;
            QUIT) END=QUIT; break ;;
        esac
    done
    echo
}
#-----------------------------------------------------------------------
# display_event_menu() - Display selections in the exit menu.
# Args:
#  $1 - Menu id string.
#-----------------------------------------------------------------------
display_exit_menu()
{
    typeset Format="%3s %-48s\n"
    typeset Item=1

    printf "$Format" " " "Item"
    printf "$Format" " " "===="

    display_menu_line $1 START ""
    display_menu_line $1 EXIT_SAVE ""
    display_menu_line $1 EXIT_NOSAVE ""
    display_menu_line $1 UP ""
    echo
}

#-----------------------------------------------------------------------
# exit_menu() - Ask the user if they really, really want to exit this
# script and whether they want to write out the conf file
# Args:
#  $1 - Path to the input conf file.
#  $2 - Path to the output conf file.
#-----------------------------------------------------------------------
exit_menu()
{
    typeset MENUTAG
    typeset CHOICE
    typeset help=\
"The emcp_mond configuration file, emcp_mond.conf, has changed.
Enter "y" to have emcp_mond pick up these changes."

    if changed_params CURR || [ "$1" != "$2" ]
    then
        while true
        do
            CHOICE=''
            display_exit_menu MENUTAG
            get_menu_choice MENUTAG 1
            case "$CHOICE" in
                START) write_conf_file $2; ${RESTART}; break ;;
                EXIT_SAVE)  write_conf_file $2; break ;;
                EXIT_NOSAVE) break ;;
                HELP) display_help "$EXIT_MENU_HELP" ;;
                UP) return 1 ;;
                QUIT) write_conf_file $2; break ;;
            esac
        done
    else
        if changed_params INIT
        then
          if askyorn y "Config file has changed.  Restart emcp_mond" "$help"
          then
              ${RESTART}
          fi
        fi
    fi
    echo
    return 0
}

#--------------------------- Parameter Names ---------------------------
MGMTSVC_NAME='remote management service'
HBT_NAME='management service heartbeat interval'
PORT_NAME='management service port'
SINGLEPATHGK_NAME='Single path gatekeeper devices'
SNMPSVC_NAME='SNMP trap generation'
PATH_DEAD_NAME='"Path Dead" event'
PATH_LIVE_NAME='"Path Alive"  event'
ALL_PATH_DEAD_NAME='"All Paths Dead" event'
NT_ALL_PATH_DEAD_NAME='"Not All Paths Dead" event'
VOL_DEAD_NAME='"Volume Dead" event'
PATH_LATENCY='"Max. Path Latency Exceeded" event'

#-----------------------------------------------------------------------
# display_menu_line() - Display a menu line in an event submenu.
# Args:
#  $1 - Name of the parameter.  Used to derive name string.
#  $2 - The current value
#-----------------------------------------------------------------------
display_value_line()
{
    eval "typeset name=\${$1_NAME}"

    printf "$Format" "$name" "$2"
}
#-----------------------------------------------------------------------
# display_changed_params - Display a summary of the parameters that have
# been changed by this edit session.  If no parameters have been changed
# no output is generated.
#-----------------------------------------------------------------------
display_changed_params()
{
    typeset -i cnt
    typeset value
    typeset Format="%-48s%-16s\n"
    typeset changed=''
    typeset tmpfile=/${TMPDIR}/conf_edit$$

    for parm in $PARAMS
    do
        cnt=0
        eval "value=\${CURR_${parm}[$cnt]}"
        while [ "$value" ]
        do
            if eval "[ \${INIT_${parm}[$cnt]} != $value ]"
            then
                case $parm in
                    MGMTSVC|SNMPSVC)
                        get_svc_value $parm svc_value
                        ;;
                    HBT)
                        get_param_value $parm svc_value minutes
                        svc_value="$svc_value"
                        ;;
                    PORT)
                        get_param_value $parm svc_value
                        ;;
                    SINGLEPATHGK)
                        get_gtk_value $parm svc_value
                        ;;
                    *DEAD|*LIVE|*LATENCY)
                        get_event_value $parm event_status timeout
                        case $cnt in
                            0) svc_value="$event_status" ;;
                            1) svc_value="$timeout" ;;
                        esac
                        ;;
                esac
                eval "name=\"\$${parm}_NAME\""
                printf "$Format" "$name" "$svc_value"
                changed=T
            fi
            cnt=$(($cnt+1))
            eval "value=\${CURR_${parm}[$cnt]}"
        done
    done > $tmpfile
    if [ "$changed" ]
    then
        echo "Changed parameters:"
        echo
        printf "$Format" "Item" "Changed Value"
        printf "$Format" "====" "============="
        cat $tmpfile
    fi
    rm -f $tmpfile
}

#-----------------------------------------------------------------------
# sol_start_daemon - On Solaris, restart the SMF service that controls
#                    emcp_mond
#-----------------------------------------------------------------------
function sol_restart_daemon
{
    if [ -x /usr/bin/svcs ]
    then
        EMCP_MOND_SVC=system/emcpower/emcp_mond
        EMCP_MOND_STATE=`/usr/bin/svcs -H -o STATE $EMCP_MOND_SVC 
                         2>/dev/null` 
        if sane_config_file
        then
            :
        else
            display_warning \
                "Configuration file settings do not allow restarting" \
                "emcp_mond."
            if [ "$EMCP_MOND_STATE" = online ]
            then
                svcadm disable $EMCP_MOND_SVC
                display_warning "Stopping emcp_mond."
            fi
            return 1
        fi

        if [ "${EMCP_MOND_STATE}" ]
        then
            echo "Refreshing $EMCP_MOND_SVC"
            svcadm refresh $EMCP_MOND_SVC
            case "${EMCP_MOND_STATE}" in
                online)
                    echo "Restarting $EMCP_MOND_SVC"
                    svcadm restart $EMCP_MOND_SVC
                    ;;
                disabled|offline)
                    echo "Starting $EMCP_MOND_SVC"
                    svcadm enable -s $EMCP_MOND_SVC
                    ;;
                maintenance)
                    display_message "Attempting to clear maintenance state."
                    svcadm clear $EMCP_MOND_SVC
                    ;;
                *)
                    display_warning "Emcp_mond service not ready to start."
                    return 1
                    ;;
            esac
            sleep 1
            case $(/usr/bin/svcs -H -o STATE $EMCP_MOND_SVC) in
                online*)
                    display_message "Emcp_mond service running."
                    ;;
                *)
                    display_warning "Emcp_mond service is not running."
                    return 1
                    ;;
            esac
        else
            display_warning "Emcp_mond service not imported."
             return 1
        fi
    else
        return 1
    fi
    return 0
}

#-----------------------------------------------------------------------
# restart_daemon_linux_systemd_support - Stop and restart emcp_mond.  We
# are assuming the start script is civilized enough to gracefully deal
# with stopping a daemon that isn't running.
#
#-----------------------------------------------------------------------
restart_daemon_linux_systemd_support()
{
    systemctl stop EmcpMond.service
    sleep 1
    if sane_config_file
    then
        systemctl start EmcpMond.service
    else
        display_message "Configuration file settings do not allow restart."
    fi
}

#-----------------------------------------------------------------------
# restart_daemon - Stop and restart emcp_mond.  We are assuming the start
# script is civilized enough to gracefully deal with stopping a daemon
# that isn't running.
#
# Args:
#  $1 = Path to daemon start script
#-----------------------------------------------------------------------
restart_daemon()
{
    $1 stop
    sleep 1
    if sane_config_file
    then
        $1 start
    else
        display_message "Configuration file settings do not allow restart."
    fi
}

check_open_ssl_installed()
{
    DISPLAY_WARNING=0
    uname -a |grep AIX > /dev/null 2>&1
    if [ "$?" = 0 ]
    then
        ls -l /usr/lib |grep libssl > /dev/null
        if [ "$?" = "0" ]
        then
            ldd /usr/sbin/emcp_mond > /dev/null 2>&1
            if [ "$?" -ne "0" ]
            then
                DISPLAY_WARNING=1
                MGMTSVC=0
            fi
        else
            DISPLAY_WARNING=1
            MGMTSVC=0
        fi
    else
        uname -a |grep Linux > /dev/null 2>&1
        if [ "$?" = 0 ]
        then
            ls -l /usr/lib64 |grep libssl > /dev/null
            if [ "$?" = "0" ]
            then
                ldd /sbin/emcp_mond |grep libssl |grep "not found" > /dev/null
                if [ "$?" = 0 ]
                then
                    DISPLAY_WARNING=1
                    MGMTSVC=0
                fi
            else
                DISPLAY_WARNING=1
                MGMTSVC=0
            fi
        fi
    fi
    if [ "${DISPLAY_WARNING}" -ne 0 ]
    then
        display_message "\n\n\tWARNING:Please install OpenSSL libraries to enable remote management service"
        DISPLAY_WARNING=0
    fi
}

#-----------------------------------------------------------------------
# get_user_input() - Display the top level menu, get the users menu
# selection, and preform the appropriate action.
# Args:
#  $1 - Input conf file name
#  $2 - Output conf file name
#-----------------------------------------------------------------------
get_user_input()
{
    typeset MENUTAG
    typeset CHOICE

    while true
    do
        CHOICE=''
        display_top_menu MENUTAG
        get_menu_choice MENUTAG
        case "$CHOICE" in
            MGMTSVC)
            TMPMGMTSVC=${MGMTSVC}
            MGMTSVC=${FLIP[$MGMTSVC]}
            DISPLAY_WARNING=0

            if [ "${TMPMGMTSVC}" = "0" ] && [ "${MGMTSVC}" = "1" ]
            then
                check_open_ssl_installed             
            fi 
            ;;
            HBT)
            if [ "${MGMTSVC}" = 0 ]
            then
                display_message "\n\tWARNING:Please enable remote management service first"
            else   
                get_heartbeat
            fi
            ;;
            PORT)
            if [ "${MGMTSVC}" = 0 ]
            then
                display_message "\n\tWARNING:Please enable remote management service first"
            else
                get_port
            fi
            ;;
            SINGLEPATHGK) SINGLEPATHGK=${FLIP[$SINGLEPATHGK]} ;;
            SNMPSVC) SNMPSVC=${FLIP[$SNMPSVC]} ;;
            PATH_DEAD) event_menu PATH_DEAD ;;
            PATH_LIVE) event_menu PATH_LIVE ;;
            ALL_PATH_DEAD) event_menu ALL_PATH_DEAD ;;
            NT_ALL_PATH_DEAD) event_menu NT_ALL_PATH_DEAD ;;
            VOL_DEAD) event_menu VOL_DEAD ;;
            PATH_LATENCY) event_menu PATH_LATENCY ;;
            SAVE) write_conf_file $2 ;;
            EXIT) END=EXIT ;;
            HELP) display_help "$TOP_MENU_HELP" ;;
            QUIT) END=QUIT ;;
             *) display_error 'Invalid selection' ;;
        esac
        if [ "$END" ]
        then
            if exit_menu $1 $2
            then
                break
            else
                END=''
            fi
        fi
    done
}

#-----------------------------------------------------------------------
# askyorn() - Ask a yes/no question and get the users response.
# Args:
#  $1 - Default choice
#  $2 - Prompt string
#  $3 - Help string
# Return
#  0 - Yes
#  1 - No
#-----------------------------------------------------------------------
askyorn()
{
    typeset ans
    typeset ret

    printf "$2 [y, n, ?] (default $1): "

    while read ans
    do
        case "${ans:-$1}" in
            y|Y) ret=0; break ;;
            n|N) ret=1; break ;;
            \?) display_help "$3" ;;
            *) display_error "Unrecognized response: $ans" ;;
        esac
        printf "$2 [y, n, ?] (default $1): "
    done
    return $ret
}

#-----------------------------------------------------------------------
# ask_num() - Prompt for a number and get the users response.
# Args:
#  $1 - Default choice
#  $2 - Prompt string
#  $3 - Help string
#-----------------------------------------------------------------------
ask_num()
{
    typeset default=$1
    typeset prompt="$2 [nn, ?] (current value: $1): "
    typeset error_msg="Garbled input.  Enter numeric characters only"

    NUM=''
    echo
    printf "$prompt "
    while read parm
    do
        case "$parm" in
            +([0-9]))
                NUM=$parm
                break
                ;;
            \?) display_help "$3" ;;
            q) break ;;
            '') NUM=$default
                break ;;
            *) display_error "$error_msg"
        esac
        echo
        printf "$prompt "
    done
}

#-----------------------------------------------------------------------
# get_delay() - Get an event timeout time from the user.
# Args:
#  $1 - Event name
#-----------------------------------------------------------------------
get_delay()
{
    eval "typeset delay=\${$1[1]}"
    typeset NUM

    while true
    do
        ask_num $delay "Enter new delay time" "$DELAY_TIME_HELP"
        if [ -z "$NUM" ] || validate_delay $NUM
        then
            break
        fi
    done
    if [ "$NUM" ]
    then
        eval "$1[1]=$NUM"
    fi
}

#-----------------------------------------------------------------------
# get_heartbeat() - Get a heartbeat time from the user.
# Args:
#  None
#-----------------------------------------------------------------------
get_heartbeat()
{
    typeset NUM

    while true
    do
        ask_num $HBT "Enter new heartbeat interval" "$HEARTBEAT_TIME_HELP"
        if [ -z "$NUM" ] || validate_heartbeat $NUM
        then
            break
        fi
    done
    if [ "$NUM" ]
    then
        HBT=$NUM
    fi
}

#-----------------------------------------------------------------------
# get_port() - Get a port number from the user.
# Args:
#  None
#-----------------------------------------------------------------------
get_port()
{
    typeset NUM

    while true
    do
        ask_num $PORT "Enter new TCP/IP port number" "$PORT_HELP"
        if [ -z "$NUM" ] || validate_port $NUM
        then
            break
        fi
    done
    if [ "$NUM" ]
    then
        PORT=$NUM
    fi
}

#-----------------------------------------------------------------------
# write_conf_file() - Write out a new conf file.
# Args:
#  $1 - Output file name.
#-----------------------------------------------------------------------
write_conf_file()
{
    typeset comment='# '
    typeset boole
    boole[0]=FALSE
    boole[1]=TRUE
    typeset MGMTSVC_LINE="MgmtComponentEnable=${boole[$MGMTSVC]}"
    typeset HBT_LINE="MgmtComponentHeartbeat=$HBT"
    typeset PORT_LINE="MgmtComponentPort=$PORT"
    typeset SINGLEPATHGK_LINE="MgmtComponentSinglePathGKOK=${boole[$SINGLEPATHGK]}"
    typeset SNMPSVC_LINE="PPSNMPTrapSvcEnable=${boole[$SNMPSVC]}"
    typeset PATH_DEAD_LINE="${comment[$PATH_DEAD]}0x2,0x4,${PATH_DEAD[1]}"
    typeset PATH_LIVE_LINE="${comment[$PATH_LIVE]}0x4,0x2,${PATH_LIVE[1]}"
    typeset ALL_PATH_DEAD_LINE="${comment[$ALL_PATH_DEAD]}0x20,0x40,${ALL_PATH_DEAD[1]}"
    typeset NT_ALL_PATH_DEAD_LINE="${comment[$NT_ALL_PATH_DEAD]}0x40,0x20,${NT_ALL_PATH_DEAD[1]}"
    typeset VOL_DEAD_LINE="${comment[$VOL_DEAD]}0x8,0x10,${VOL_DEAD[1]}"
    typeset PATH_LATENCY_LINE="${comment[$PATH_LATENCY]}0x80000,0x80000,0"

    display_message "Writing configuration file."
    if [ -f "$1" ]
    then
        mv $1 $1.bak
    fi

    cat <<ZZZ > "$1"
#
# emcp_mond.conf
# Configuration file for the Dell EMC PowerPath Remote Management Service
#

# Parameters for remote management service
#
# To enable the remote management service, uncomment the "enable" line below.
# If you want to use "heartbeat" or "port" values other than the default
# values, uncomment the lines below and change the desired value.
# For heartbeat, the value must be greater than 0 and less than 60.
# The default value is 10 minutes.  For port, the default
# value is 9083.  
#
# By default, the remote management service does not issue a warning
# when it detects a gatekeeper device configured with one path.  If all
# of your gatekeeper devices are configured with multiple paths, set
# MgmtComponentSinglePathGKOK to FALSE.

${MGMTSVC_LINE}
${HBT_LINE}
${PORT_LINE}
${SINGLEPATHGK_LINE}
ZZZ

if [ "$SNMP_OK" ]
then
cat <<ZZZ >> "$1"
#------------------------------------------------------------------------
# Parameters for SNMP trap processing
#
# To enable the generation of SNMP traps, uncomment the "enable" line below.

${SNMPSVC_LINE}

# The kernel events below are processed only by SNMP.

# --- Kernel events ---

# The kernel events below are processed by the remote management service
# and by SNMP.
#
# The format for each pair of events to monitor is event1,event,time_in_secs.
# event1 and event2 are hex representations of an event.
# EMCP_PATH_IS_DEAD for instance.
#
# event1 is the event to track/monitor.
# event2 is the event that voids event1 IF it occurs within time_in_secs.
#
# Note: All lines beginning with a '#' will be ignored by the daemon.
#

#
# Event-pair #1
# EMCP_EVENT_MP_PATH_IS_DEAD, EMCP_EVENT_MP_PATH_IS_ALIVE, 60secs
#

${PATH_DEAD_LINE}

#
# Event-pair #2
# EMCP_EVENT_MP_PATH_IS_ALIVE, EMCP_EVENT_MP_PATH_IS_DEAD, 60secs
#

${PATH_LIVE_LINE}

#
# Event-pair #3
# EMCP_EVENT_MP_ALL_PATHS_DEAD, EMCP_EVENT_MP_NOT_ALL_PATHS_DEAD, 300secs
#

${ALL_PATH_DEAD_LINE}

#
# Event-pair #4
# EMCP_EVENT_MP_NOT_ALL_PATHS_DEAD, EMCP_EVENT_MP_ALL_PATHS_DEAD, 300secs
#

${NT_ALL_PATH_DEAD_LINE}

#
# Event-pair #5
# EMCP_EVENT_MP_VOL_IS_DEAD, EMCP_EVENT_MP_VOL_IS_ALIVE, 300secs
#

${VOL_DEAD_LINE}

#
# Event-pair #6
# EMCP_EVENT_MP_PATH_LATENCY_MAX_EXCEEDED, EMCP_EVENT_MP_PATH_LATENCY_MAX_EXCEEDED, 0secs
#

${PATH_LATENCY_LINE}

#
# Event-pair #7
# EMCP_EVENT_MP_BUS_IS_DEAD, EMCP_EVENT_MP_BUS_IS_ALIVE, 0secs
#

0x80,0x00100000,0

#
# Event-pair #8
# EMCP_EVENT_MP_BUS_IS_ALIVE, EMCP_EVENT_MP_BUS_IS_DEAD, 0secs
#

0x00100000,0x80,0


#
# EOF
#
ZZZ
fi
## Reset initial values of parms so we don't ask about saving the file
## twice in a row.

backup_params CURR
}

#-----------------------------------------------------------------------
# init_event_parms() - Processing for event lines. Validate event timeout
# and mark enabled/disabled.
#
# Args:
#  $1 - Line read from config file
#  $2 - Variable to be receive event values
#  $3 - User friendly name of event
#-----------------------------------------------------------------------
init_event_parms()
{
    delay=${1##*,}
    if validate_delay $delay
    then
      :
    else
      display_error "Invalid delay in conf file for \"$3\""
      delay=60
    fi
    case "$1" in
      \#*) status=0 ;;
      0*) status=1 ;;
    esac
    echo "$2[0]=$status"
    echo "$2[1]=$delay"
 }

#-----------------------------------------------------------------------
# conf_file_stream() - Read parameters from a conf file and write variable
# assignments to stdout.
# Args:
#  $1 - Input file name.
#-----------------------------------------------------------------------
conf_file_stream()
{
    typeset WSP=" 	"  ## Space and tab

    sed -e "s/[${WSP}][${WSP}]*//g" \
        -e 's/^##*/#/' $1 | \
    ${TR} "[:lower:]" "[:upper:]" | \
    while read line
    do
        case "$line" in
            MGMTCOMPONENTENABLE=TRUE) echo MGMTSVC=1 ;;
            MGMTCOMPONENTENABLE=*)    echo MGMTSVC=0 ;;
            PPSNMPTRAPSVCENABLE=TRUE)   echo SNMPSVC=1 ;;
            PPSNMPTRAPSVCENABLE=*)      echo SNMPSVC=0 ;;
            MGMTCOMPONENTSINGLEPATHGKOK=TRUE) echo SINGLEPATHGK=1 ;;
            MGMTCOMPONENTSINGLEPATHGKOK=*) echo SINGLEPATHGK=0 ;;
            MGMTCOMPONENTHEARTBEAT=*)
                        if validate_heartbeat ${line##*HEARTBEAT=}
                        then
                            echo HBT=${line##*HEARTBEAT=}
                        else
                            display_error "Invalid heartbeat in conf file."
                        fi
                        ;;
            MGMTCOMPONENTPORT=*)
                    if validate_port ${line##*PORT=}
                    then
                        echo PORT=${line##*PORT=}
                    else
                        display_error "Invalid port in conf file."
                    fi
                    ;;
            @(#|)0X2,0X4,*) init_event_parms \
                                        $line \
                                        PATH_DEAD \
                                        "Path Dead" ;;
            @(#|)0X4,0X2,*) init_event_parms \
                                        $line \
                                        PATH_LIVE \
                                        "Path Alive" ;;
            @(#|)0X20,0X40,*) init_event_parms \
                                        $line \
                                        ALL_PATH_DEAD \
                                        "All Paths Dead" ;;
            @(#|)0X40,0X20,*) init_event_parms \
                                        $line \
                                        NT_ALL_PATH_DEAD \
                                        "Not All Paths Dead" ;;
            @(#|)0X8,0X10,*) init_event_parms \
                                        $line \
                                        VOL_DEAD \
                                        "Volume Dead" ;;
            @(#|)0X80000,0X80000,*) init_event_parms \
                                        $line \
                                        PATH_LATENCY \
                                        "Maximum Path Latency Exceeded" ;;
        esac
    done
}

#-----------------------------------------------------------------------
# read_conf_file() - Read parameters from a conf file.
# Args:
#  $1 - Input file name.
#-----------------------------------------------------------------------
read_conf_file()
{
    eval $(conf_file_stream $1)
}

#-----------------------------------------------------------------------
# backup_params() - Save the value of each parameter, PARAM, in a variable
# named INIT_PARAM.
# Args:
#  $1 - Param set, either INIT or CURR
#  PARAMS - A list of all parameter names
#-----------------------------------------------------------------------
backup_params()
{
    typeset -i cnt
    typeset value

    for parm in $PARAMS
    do
        cnt=0
        eval "value=\$$parm"
        while [ "$value" ]
        do
            eval "${1}_${parm}[$cnt]=$value"
            cnt=$(($cnt+1))
            eval "value=\${$parm[$cnt]}"
        done
    done
}

#-----------------------------------------------------------------------
# changed_params() - Determine if any parameters have changed value.
# Args:
#  $1 - Param set, either INIT or CURR
#  PARAMS - A list of all parameter names
# Return:
#  0 - At least one value has changed.
#  1 - No values have changed.
#-----------------------------------------------------------------------
changed_params()
{
    typeset -i cnt
    typeset value

    for parm in $PARAMS
    do
        cnt=0
        eval "value=\$$parm"
        while [ "$value" ]
        do
            eval "[ \${${1}_${parm}[$cnt]} = $value ]" || return 0
            cnt=$(($cnt+1))
            eval "value=\${$parm[$cnt]}"
        done
    done
    return 1
}

#-----------------------------------------------------------------------
# sane_config_file() - Return a true status if the current setting of
# config file parameters will allow the daemon to run.  With performance
# code added to emcp_mond, it will always run even of the host management
# and SNMP services are disabled.
#-----------------------------------------------------------------------
function sane_config_file
{
        return 0
}

##-------------------------------- Main --------------------------------

## set -x
## typeset -ft `typeset +f`

## Require rootness

if [ "${CONF_DIR}" = "$platf_conf_dir" ]
then
    if [ $(${ID} -u) -ne 0 ]
    then
        display_fatal_error "Root uid required."
    fi
fi

## Default parameter values

MGMTSVC=0
PORT=9083
HBT=10
SINGLEPATHGK=1
SNMPSVC=0
PATH_DEAD[0]=1
PATH_DEAD[1]=60
PATH_LIVE[0]=0
PATH_LIVE[1]=60
ALL_PATH_DEAD[0]=1
ALL_PATH_DEAD[1]=300
NT_ALL_PATH_DEAD[0]=0
NT_ALL_PATH_DEAD[1]=300
VOL_DEAD[0]=0
VOL_DEAD[1]=300
PATH_LATENCY[0]=0
PATH_LATENCY[1]=0

# Each parameter, PARAM, has a prompt string, PARAM_PRMPT, used in the menus
# and a conf file line string, PARAM_LINE, used in writing out the changed
# conf. file.

PARAMS="MGMTSVC \
    HBT \
    PORT \
    SINGLEPATHGK \
    SNMPSVC \
    PATH_DEAD \
    PATH_LIVE \
    ALL_PATH_DEAD \
    NT_ALL_PATH_DEAD \
    VOL_DEAD \
    PATH_LATENCY"

FLIP[0]=1
FLIP[1]=0

CONF_PATH_OUT="$CONF_DIR/$CONF_FILE"
if [ -r "$CONF_PATH_OUT" ]
then
    CONF_PATH_IN="$CONF_PATH_OUT"
    [ -w "$CONF_PATH_OUT" ] || readonly=T
else
    if [ -r "$CONF_SAMPLE" ]
    then
        CONF_PATH_IN="$CONF_SAMPLE"
    else
        display_fatal_error "Configuration file not found"
    fi
    [ -w $(dirname $CONF_PATH_OUT) ] || readonly=T
fi

if [ "$readonly" ]
then
    display_top_menu MENUTAG

    display_warning 'Configuration file is not writable: $CONF_PATH_OUT'
    echo
else
    read_conf_file $CONF_PATH_IN

    ## Remember initial param values (INIT) and param values last
    ## written to conf. file (CURR).

    backup_params INIT
    backup_params CURR

    get_user_input $CONF_PATH_IN $CONF_PATH_OUT
    display_changed_params
fi

exit
