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

PATH=/usr/bin:/bin:/usr/sbin/:/sbin; export PATH

PP_MGMT_SERVICE_STARTED_MARKER_FILE="/etc/opt/emcpower/.pp_mgmt_svc_started"

if [ "`uname`" == "AIX" ]
then
    lsdev -Ccdriver -tpower | grep Available > /dev/null
    if [ "$?" -ne 0 ]
    then
        echo "PowerPath base driver not configured. Please execute powermt config before retry"
        exit 1
    fi
fi

: ${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
ADD_HOST_ENABLE=''

case `uname` in
    Linux)
        ADD_HOST_ENABLE=T
        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 "%s" "$*"
    echo
    echo
}

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

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

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

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

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

ADD_HOST_PRMPT='Add host to a PowerPath Management Appliance instance'
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'
SNMP_PRMPT='Change SNMP configuration'
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()
{
    local get_value=$1
    eval "typeset status=\$${get_value}"
    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()
{
    local gtk_value=$1
    typeset allow
    allow[0]="Warn"
    allow[1]="Allow"
    eval "typeset status=\$${gtk_value}"
    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()
{
    local value=$1
    eval "typeset status=\$$value"
    eval "$2=\"${STATE[$status]}\""
    eval "$3=\"delay \${${value}[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()
{
    local id=$1
    local string=$2
    local cur_value=$3
    eval "typeset prompt=\${${string}_PRMPT}"

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

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

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

    if [ "$ADD_HOST_ENABLE" ]
    then
        display_menu_line $menu_id ADD_HOST ""
    fi
    get_svc_value MGMTSVC svc_value
    display_menu_line $menu_id MGMTSVC "$svc_value"
    get_param_value HBT param_value minutes
    display_menu_line $menu_id HBT "$param_value"
    get_param_value PORT param_value
    display_menu_line $menu_id PORT "$param_value"
    get_gtk_value SINGLEPATHGK param_value
    display_menu_line $menu_id SINGLEPATHGK "$param_value"
    if [ "$SNMP_OK" ]
    then
        display_menu_line $menu_id SNMP ""
    fi
    display_menu_line $menu_id SAVE ""
    display_menu_line $menu_id 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()
{
    local id=$1
    local menu=$2
    typeset select
    typeset choice
    typeset default

    if [ "$menu" ]
    then
        default=$menu
    else
        default=n
    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=\${$id[$select]}"
                if [ "$choice" ]
                then
                    CHOICE=$choice
                    break
                else
                    display_error "Invalid selection: $select"
                fi
                ;;
           '')  if [ "$menu" ]
                then
                    eval "CHOICE=\${$id[$menu]}"
                    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()
{
    local id=$1
    local menu=$2
    typeset Format="%3s %-48s%-16s\n"
    typeset Item=1
    eval "typeset event_name=\$${menu}_NAME"
    eval "typeset status=\$${menu}"
    eval "typeset delay=\${${menu}[1]}"

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

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

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

    while true
    do
        CHOICE=''
        display_event_menu MENUTAG $event_name
        get_menu_choice MENUTAG 3
        case "$CHOICE" in
            EVENT) eval "$event_name=\${FLIP[\$$event_name]}" ;;
            DELAY) get_delay $event_name ;;
            HELP) display_help "$EVENT_MENU_HELP" ;;
            UP) break ;;
            QUIT) END=QUIT; break ;;
        esac
    done
    echo
}

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

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

    get_svc_value SNMPSVC svc_value
    display_menu_line $id SNMPSVC "$svc_value"
    get_event_value PATH_DEAD event_status timeout
    display_menu_line $id PATH_DEAD "$event_status, $timeout"
    get_event_value PATH_LIVE event_status timeout
    display_menu_line $id PATH_LIVE "$event_status, $timeout"
    get_event_value ALL_PATH_DEAD event_status timeout
    display_menu_line $id ALL_PATH_DEAD "$event_status, $timeout"
    get_event_value NT_ALL_PATH_DEAD event_status timeout
    display_menu_line $id NT_ALL_PATH_DEAD \
                                    "$event_status, $timeout"
    get_event_value VOL_DEAD event_status timeout
    display_menu_line $id VOL_DEAD "$event_status, $timeout"
    get_event_value PATH_LATENCY event_status timeout
    display_menu_line $id PATH_LATENCY "$event_status, $timeout"
    display_menu_line $id UP ""
    echo
}

#-----------------------------------------------------------------------
# snmp_menu() - Display snmp menu, get the users menu selection,
# and preform the appropriate action.
# Args:
#  $1 - Event name
#-----------------------------------------------------------------------
snmp_menu()
{
    local event_name=$1
    typeset MENUTAG
    typeset CHOICE

    while true
    do
        CHOICE=''
        display_snmp_menu MENUTAG $event_name
        get_menu_choice MENUTAG 8
        case "$CHOICE" in
            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 ;;
            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()
{
    local id=$1
    typeset Format="%3s %-48s\n"
    typeset Item=1

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

    display_menu_line $id START ""
    display_menu_line $id EXIT_SAVE ""
    display_menu_line $id EXIT_NOSAVE ""
    display_menu_line $id 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()
{
    local in_file=$1
    local out_file=$2
    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 || [ "$in_file" != "$out_file" ]
    then
        while true
        do
            CHOICE=''
            display_exit_menu MENUTAG
            get_menu_choice MENUTAG 1
            case "$CHOICE" in
                START) write_conf_file $out_file; ${RESTART}; break ;;
                EXIT_SAVE)  write_conf_file $out_file; break ;;
                EXIT_NOSAVE) break ;;
                HELP) display_help "$EXIT_MENU_HELP" ;;
                UP) return 1 ;;
                QUIT) write_conf_file $out_file; 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'
SNMP='Change SNMP configuration'
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()
{
    local param=$1
    local cur_value=$2
    eval "typeset name=\${${param}_NAME}"

    printf "$Format" "$name" "$cur_value"
}
#-----------------------------------------------------------------------
# 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()
{
    local path=$1
    $path stop
    sleep 1
    if sane_config_file
    then
        $path 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
}

enable_disable_remote_management_service()
{
    local value=$1
    TMPMGMTSVC=${MGMTSVC}
    MGMTSVC=$value
    DISPLAY_WARNING=0

    if [ "${TMPMGMTSVC}" = "0" ] && [ "${MGMTSVC}" = "1" ]
    then
        check_open_ssl_installed
    fi
}

#------------------------------------------------------------------------------
# validate_ppma_ip() - Validate Powerpath Management Appliance(PPMA) ip address 
#------------------------------------------------------------------------------
validate_ppma_ip()
{
    if expr "$ppma_ip" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
        for j in 1 2 3 4; do
            if [ $(echo "$ppma_ip" | cut -d. -f$j) -gt 255 ]; then
                return 1
            fi
        done
        return 0
    else
        return 1
    fi
}

#----------------------------------------------------------------------------------------
# read_and_validate_host_info() - Read  PowerPath Management Appliance(PPMA) host details
# Get PPMA ip, username, password of PPMA host as user input.
#----------------------------------------------------------------------------------------
read_and_validate_host_info()
{
    echo
    echo "Enter following PPMA host information:"
    for i in 1 2 3; do
        flag=0
        read -p "Enter PPMA IP: " ppma_ip
        if [ ! -z $ppma_ip ]; then
            validate_ppma_ip $ppma_ip
            result=$?
            if [ $result == 0 ]; then
                break
            else
               flag=1
               display_error "PPMA IP address is not valid. Enter valid IP address."
            fi
        else
            flag=1
            display_error "PPMA IP address is empty. Enter valid IP address."
        fi
        if [ $i == 3 ] && [ $flag == 1 ]; then
            exit
        fi
    done

    for k in 1 2 3; do
        flag=0
        read -p "Enter PPMA username: " user_var
        read -sp "Enter PPMA password: " pass_var
        if  [ ! -z $user_var ] && [ ! -z $pass_var ]; then
            break
        else
            flag=1
            echo
            display_error "PPMA username or password is empty. Enter valid username and password."
        fi
        if [ $k == 3 ] && [ $flag == 1 ]; then
            exit
        fi
    done
}

#--------------------------------------------------------------------------------
# add_host_to_ppma() - Add PowerPath host to PowerPath Management Appliance(PPMA)
# Steps:
# 1. Authenticate to PPMA host using REST API.
# 2. Generate server key using OpenSSL.
# 3. Generate server certificate signing request and send it to PPMA using REST API.
# 4. Receive server cert, CA and PPMA certs from PPMA and store in /etc/opt/emcpower.
#    Combine server and key into a single .pem file.
# 5. Send discover host request to PPMA using REST API. 
#--------------------------------------------------------------------------------
add_host_to_ppma()
{
    tmp_dir=/etc/opt/emcpower/.tmp
    err=0
    cookie_file=$tmp_dir/cookie.txt
    read_and_validate_host_info
    echo
    echo $ppma_ip > /etc/emc/ppma_ip
    chmod 600 /etc/emc/ppma_ip > /dev/null 2>&1
    echo j_password=$pass_var > $tmp_dir/cred.txt

    hostname=`hostname --fqdn`

    url_auth="https://$ppma_ip/LicenseReportingApplication/authenticate"
    url_generate_cert="https://$ppma_ip/LicenseReportingApplication/rest/hosts/nonesx/sign/ppcert"
    url_host_discover="https://$ppma_ip/LicenseReportingApplication/rest/hosts/nonesx/discover"

    # Authenticate to PPMA host using REST API. 
    url_auth_response=`curl --connect-timeout 10 -c $cookie_file -k -w "%{http_code}\n" -L $url_auth -d j_username=$user_var -d @$tmp_dir/cred.txt -s -o /dev/null`

    if [ $url_auth_response == 200 ]; then
        rm -rf $tmp_dir/cred.txt > /dev/null 2>&1
        echo
        echo "Generate server key."
        openssl genrsa -out $tmp_dir/server.key 4096 > /dev/null 2>&1

        if [ -s $tmp_dir/server.key ]; then
            display_message "Server key generated successfully."
            echo "Create server certificate signing request."
            openssl req -new -key $tmp_dir/server.key -out $tmp_dir/server.csr

            if [  -s $tmp_dir/server.csr ]; then
                display_message "Created server certificate signing request successfully."
                url_generate_cert_response=`curl -b $cookie_file -k -w "%{http_code}\n" -L -F 'certstream=@/etc/opt/emcpower/.tmp/server.csr' \
                                            -F host=$hostname $url_generate_cert -o /$tmp_dir/combinecert.pem  -s -o /dev/null`

                if [ $url_generate_cert_response == 200 ]; then
                    ppcert=`cat $tmp_dir/combinecert.pem | tr { '\n' | tr , '\n' | tr } '\n' | grep "ppcert" | awk  -F'"' '{print $4}'`
                    cacert=`cat $tmp_dir/combinecert.pem | tr { '\n' | tr , '\n' | tr } '\n' | grep "cacert" | awk  -F'"' '{print $4}'`
                    ppmacert=`cat $tmp_dir/combinecert.pem | tr { '\n' | tr , '\n' | tr } '\n' | grep "ppmacert" | awk  -F'"' '{print $4}'`
                    echo $ppcert | sed 's/\\n/\'$'\n''/g' | sed '/^$/d' > $tmp_dir/server.crt
                    echo $cacert | sed 's/\\n/\'$'\n''/g' | sed '/^$/d' > /etc/opt/emcpower/cacert.pem
                    echo $ppmacert | sed 's/\\n/\'$'\n''/g' | sed '/^$/d' > /etc/opt/emcpower/ppmacert.pem
                    cat $tmp_dir/server.key $tmp_dir/server.crt > /etc/opt/emcpower/server.pem
                    chmod 600 /etc/opt/emcpower/server.pem /etc/opt/emcpower/cacert.pem /etc/opt/emcpower/ppmacert.pem $tmp_dir/server.csr
                    display_message "Successfully created server, CA and PPMA certificates."
                else
                    display_error "Failed to generate server, CA and PPMA certificates."
                fi
            else
                display_error "Failed to generate server certificate signing request."
            fi
        else
             display_error "Failed to generate server key."
        fi
       
        rm -rf $tmp_dir/combinecert.pem > /dev/null 2>&1
        rm -rf $tmp_dir/server.key > /dev/null 2>&1
        rm -rf $tmp_dir/server.crt  > /dev/null 2>&1

        # Write to configuratioon file
        write_conf_file $CONF_PATH_OUT

        # restart emcp_mond daemon
        display_message "Restarting emcp_mond daemon."
        ${RESTART};

        #
        # Sometimes its observed that the host agent (remote management service component of emcp_mond)
        # takes a little bit of time to get fully started after the above restart of emcp_mond daemon.
        #
        # This could happen if there are lot of network connections on the host or if the DNS config is
        # not correct.  In such cases, APIs like getaddrinfo() and gethostid() that are called during
        # remote management service startup take time to complete delaying the start of the service.
        # But when the remote management service is fully started, it will create a marker file.
        #
        # Hence check if the management service has started fully by checking for the marker file for
        # upto 60 seconds.
        #
        count=1
        while true
        do
            if [ -f $PP_MGMT_SERVICE_STARTED_MARKER_FILE ]
            then
                break
            fi

            count=$((count+1))
            if [ $count -gt 60 ]
            then
                display_message "PowerPath Management service did not start properly."
                /usr/bin/logger -t PowerPath "PowerPath Management service did not start properly."
                break
            fi

            sleep 1
        done

        url_host_discover_response=`curl -b $cookie_file -k -w "%{http_code}\n" -L  -H "Content-Type: application/x-www-form-urlencoded" \
                                    -d "host=$hostname&port=$PORT" $url_host_discover -s -o /dev/null`

        if [ $url_host_discover_response == 201 ]; then
            display_message "Connection established successfully. Remote host ip: $ppma_ip."
            /usr/bin/logger -t PowerPath "Connection established successfully. Remote host ip: $ppma_ip."
        elif [ $url_host_discover_response == 202 ]; then
            display_message "Connection re-established successfully. Remote host ip: $ppma_ip."
            /usr/bin/logger -t PowerPath "Connection re-established successfully. Remote host ip: $ppma_ip."
        else
            display_error "Not able to establish the connection ($url_host_discover_response). Remote host ip: $ppma_ip."
            err=$?
            /usr/bin/logger -t PowerPath "Error: Not able to establish the connection ($url_host_discover_response). Remote host ip: $ppma_ip."
        fi
    else
        rm -rf $tmp_dir/cred.txt > /dev/null 2>&1
        echo
        display_error "Failed to establish the connection. Please verify PPMA credentials."
        /usr/bin/logger -t PowerPath "Error: Failed to establish the connection. Please verify PPMA credentials."
    fi

    rm -rf $cookie_file  > /dev/null 2>&1
    return $err
}

#-----------------------------------------------------------------------
# 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()
{
    local in_file=$1
    local out_file=$2
    typeset MENUTAG
    typeset CHOICE
    ENABLED=1

    while true
    do
        CHOICE=''
        display_top_menu MENUTAG
        get_menu_choice MENUTAG
        case "$CHOICE" in
            ADD_HOST)
            if [ "${MGMTSVC}" = 0 ]
            then
                if askyorn y "Remote management service is currently disabled. Do you want to enable it?" "$help"
                then
                    ENABLED=1
                    enable_disable_remote_management_service 1
                else
                    ENABLED=0
                    display_message "\n\tWarning: Can not add host without enabling remote management service."
                fi
            fi
            if [ $ENABLED == 1 ]
            then
                add_host_to_ppma
                if [ $? == 1 ] ; then
                    display_message "Failed to connect to PPMA instance and hence remote management service will be disabled."
                    enable_disable_remote_management_service 0
                    write_conf_file $out_file;
                    display_message "Restarting emcp_mond daemon."
                    ${RESTART};
                fi
                exit
            fi
            ;;
            MGMTSVC)
            if [ "${MGMTSVC}" = 0 ]
            then
                enable_disable_remote_management_service 1
            else
                enable_disable_remote_management_service 0
            fi
            ;;
            HBT)
            if [ "${MGMTSVC}" = 0 ]
            then
                if askyorn y "Remote management service is currently disabled. Do you want to enable it?" "$help"
                then
                    ENABLED=1
                    enable_disable_remote_management_service 1
                else
                    ENABLED=0
                    display_message "\n\tWarning: Can not change heartbeat without enabling remote management service."
                fi
            fi
            if [ $ENABLED == 1 ]
            then
                get_heartbeat
            fi
            ;;
            PORT)
            if [ "${MGMTSVC}" = 0 ]
            then
                if askyorn y "Remote management service is currently disabled. Do you want to enable it?" "$help"
                then
                    ENABLED=1
                    enable_disable_remote_management_service 1
                else
                    ENABLED=0
                    display_message "\n\tWarning: Can not change port number without enabling remote management service."
                fi
            fi
            if [ $ENABLED == 1 ]
            then
                get_port
            fi
            ;;
            SINGLEPATHGK) SINGLEPATHGK=${FLIP[$SINGLEPATHGK]} ;;
            SNMP) snmp_menu SNMP ;;
            SAVE) write_conf_file $out_file ;;
            EXIT) END=EXIT ;;
            HELP) display_help "$TOP_MENU_HELP" ;;
            QUIT) END=QUIT ;;
             *) display_error 'Invalid selection' ;;
        esac
        if [ "$END" ]
        then
            if exit_menu $in_file $out_file
            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()
{
    local def_value=$1
    local prompt_str=$2
    local help_str=$3
    typeset ans
    typeset ret

    printf "$prompt_str [y, n, ?] (default $def_value): "

    while read ans
    do
        case "${ans:-$def_value}" in
            y|Y) ret=0; break ;;
            n|N) ret=1; break ;;
            \?) display_help "$help_str" ;;
            *) display_error "Unrecognized response: $ans" ;;
        esac
        printf "$prompt_str [y, n, ?] (default $def_value): "
    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()
{
    local prompt_str=$2
    local help_str=$3
    typeset default=$1
    typeset prompt="$prompt_str [nn, ?] (current value: $default): "
    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 "$help_str" ;;
            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()
{
    local event_name=$1
    eval "typeset delay=\${$event_name[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 "$event_name[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()
{
    local out_file=$1
    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 "$out_file" ]
    then
        mv $out_file $out_file.bak
    fi

    cat <<ZZZ > "$out_file"
#
# emcp_mond.conf
# Configuration file for the Dell 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 >> "$out_file"
#------------------------------------------------------------------------
# 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.
chmod 600 $out_file >/dev/null 2>&1
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()
{
    local conf_file=$1
    local var_value=$2
    local event_name=$3
    delay=${conf_file##*,}
    if validate_delay $delay
    then
      :
    else
      display_error "Invalid delay in conf file for \"$event_name\""
      delay=60
    fi
    case "$conf_file" in
      \#*) status=0 ;;
      0*) status=1 ;;
    esac
    echo "$var_value[0]=$status"
    echo "$var_value[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()
{
    local in_file=$1
    typeset WSP=" 	"  ## Space and tab

    sed -e "s/[${WSP}][${WSP}]*//g" \
        -e 's/^##*/#/' $in_file | \
    ${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()
{
    local in_file=$1
    eval $(conf_file_stream $in_file)
}

#-----------------------------------------------------------------------
# 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
