#!/bin/bash
#
# DT Configuration Scriptlet

# $Id: DTSetup 635 2007-09-17 16:34:31Z mschultheiss@doubletake.com $

# Get branding-related environment
source /usr/share/DTBrand.sh

SCRIPT_NAME="${0##*/}"
SERVICE_DISPLAY_NAME="${DTBRAND_DISPLAY_NAME_IN_TEXT_UI}"
EULA_NAME="${DTBRAND_PRODUCT_NAME}"
DAEMON_BINARY_NAME="${DTBRAND_DAEMON_BINARY_NAME}"
SERVICE_ALIAS="${DTBRAND_SERVICE_ALIAS}"
INSTALL_SUBDIR="${DTBRAND_PATH_SUBDIR}"
CONFIG_DIR="/etc/${INSTALL_SUBDIR}"
RPM_PACKAGE_NAME="${DTBRAND_RPM_PACKAGE_NAME}"
DEFAULT_CONF_FILE="/etc/${INSTALL_SUBDIR}/${DAEMON_BINARY_NAME}.conf"
CONF_FILE="${DEFAULT_CONF_FILE}"
ACTIVATION_CODE="ActivationCode"
BACKUP_CONF_FILE_EXT="backup"
DTFS_MOUNTS="${CONFIG_DIR}/dtfs_mounts"
DTLOOP_MOUNTS="${CONFIG_DIR}/dtloop_devices"
PROC_DTFS_MOUNTS=/proc/dtfs/mounts
PROC_DTREP_CONTROL=/proc/dtrep/control
DTREP_SETTINGS="$CONFIG_DIR/dtrep_settings"
KERNEL_VERSION=$(uname -r)
KERNEL_MODULE_DIR=/lib/modules/"$KERNEL_VERSION"/kernel/fs
EULA_FILE="/etc/${INSTALL_SUBDIR}/Read_And_Accepted_Double-Take_Software_End_User_License_Agreement"
ACCEPT_EULA=
IO_CONTROL_INTERVAL_MAX=10000 # 10 seconds
MEMORY_LIMIT_MIN=$(( 4 * 1024 )) # 4 kB
MEMORY_LIMIT_MAX=$(( 1024 * 1024 * 1024 )) # 1 GB
WRITE_CHUNK_SIZE_MAX=$(( 1024 * 1024 )) # 1 MB
FIREWALL="0" # '0' is the default value

# The next few functions report problems, including the script name and the
# current process ID, to the system log (and sometimes stderr as well).  The
# default facility and priority are "user" and "notice".

grumble () {
    # Complain about the arguments to the system log.
    logger -i -t "$SCRIPT_NAME" "$*"
}

squawk () {
    # Screech the arguments to stderr and the system log.
    logger -i -s -t "$SCRIPT_NAME" "$*"
}

howl () {
    # Shout the arguments to stderr and the system log with a scary prefix.
    logger -i -s -p user.warning -t "$SCRIPT_NAME" "WARNING: $*"
}

load_dt_kernel_modules () {
    DTInit.sh -l
}

mount_and_register_file_systems () {
    DTInit.sh -m
}

attach_and_register_block_devices () {
    DTInit.sh -a
}

unregister_and_unmount_file_systems () {
    DTInit.sh -u
}

unregister_and_detach_block_devices () {
    DTInit.sh -d
}

get_date () {
    # Report date in ISO 8601 format
    date "+%Y.%m.%d-%H.%M.%s"
}

insert_key () {
    if [ -n "$INTERACTIVE" ]; then
        clear
        echo $"The activation code authenticates this installation for use."
        echo
        echo $"Press Enter to keep the current activation code."
        ACTIVATION_KEY=$(grep "$ACTIVATION_CODE" "$CONF_FILE" 2>/dev/null | awk -F\  '{print $2}')
        read -e -p $"Please enter the $SERVICE_DISPLAY_NAME activation code ["$ACTIVATION_KEY"]: " ENTRY
    else
        ENTRY="$ACTIVATION_KEY"
    fi
    if [ -n "$ENTRY" ]; then
        # Backup the conf file
        if [ -e "$CONF_FILE" ]; then
            BACKUP_FILE="${CONF_FILE}.${BACKUP_CONF_FILE_EXT}-$(get_date)"
            mv "$CONF_FILE" "$BACKUP_FILE"

            # Extract all other options except the activation code
            grep -v "$ACTIVATION_CODE" "$BACKUP_FILE" >"$CONF_FILE"
        fi

        # Append code to end of file
        echo "$ACTIVATION_CODE $ENTRY" >>"$CONF_FILE"
        echo $"Activation code inserted into the configuration file."
        echo $"If $SERVICE_DISPLAY_NAME is already running, please restart it now."
    else
        echo $"Activation code not changed."
    fi
}

eula_accept () {
    SLAM_DOOR_IN_FACE=
    while :; do
        ACCEPT_EULA=$(echo "$ACCEPT_EULA" | tr '[:upper:]' '[:lower:]')
        case "$ACCEPT_EULA" in
            yes)
                >"$EULA_FILE"
                break
                ;;
            '') # empty string
                if [ -n "$INTERACTIVE" ]; then
                    clear
                    read -e -p$"Press Enter to view the ${EULA_NAME} End User License Agreement: " READ_ENTER
                    if [ -x /usr/bin/less ]; then
                        less -Ps"[Press space to continue, 'q' when done.]" /usr/share/doc/${INSTALL_SUBDIR}/license.txt
                    elif [ -x /bin/more ]; then
                        more -d /usr/share/doc/${INSTALL_SUBDIR}/license.txt
                    else
                        echo $"Please install either less or more and restart DTSetup."
                        exit 0;
                    fi
                    echo      $"Type YES if you have read and accepted the "
                    read -e -p$"${EULA_NAME} End User License Agreement: " ACCEPT_EULA
                else
                
                    SLAM_DOOR_IN_FACE=yes
                fi
                ;;
            *)
                SLAM_DOOR_IN_FACE=yes
                ;;
        esac
        if [ -n "$SLAM_DOOR_IN_FACE" ]; then
            echo $"${EULA_NAME} EULA not accepted. Run DTSetup again to accept."
            exit 0
        fi
    done
}

add_remove_user () {
    RHEL_OR_SLES=$(rpm -q sles-release | grep "not installed")
    GROUPMOD="groupmod -R"
    if [ -n "$RHEL_OR_SLES" ]; then
        GROUPMOD="gpasswd -d"
    fi 
    while :; do
        clear
        echo $"=== Add/Remove User  ==="
        echo
        echo $"$SERVICE_DISPLAY_NAME Administrators are needed to authorize"
        echo $"   replication set configuration activities in"
        echo $"   DTCL and the Windows consoles."
        echo $"$SERVICE_DISPLAY_NAME Monitors can only view status information."
        echo
        # Output the current set of admins and monitors
        echo $"$SERVICE_DISPLAY_NAME Administrators: $(getent group dtadmin | awk -F: '{print $4}')"
        echo $"$SERVICE_DISPLAY_NAME Monitors: $(getent group dtmon | awk -F: '{print $4}')"
        echo
        echo $"==================================="
        echo $"Menu Options"
        echo $"1.    Add $SERVICE_DISPLAY_NAME Administrator"
        echo $"2.    Remove $SERVICE_DISPLAY_NAME Administrator"
        echo $"3.    Add $SERVICE_DISPLAY_NAME Monitor"
        echo $"4.    Remove $SERVICE_DISPLAY_NAME Monitor"
        echo $"Q.    Exit the Add/Remove User Menu"
        echo
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                read -e -p $"Please enter the Administrative username to add : " USER_NAME
                if [ -n "$RHEL_OR_SLES" ]; then
                   usermod -a -G dtadmin $USER_NAME
                else
                   groupmod -A $USER_NAME dtadmin
                fi
                ;;
            2)
                read -e -p $"Please enter the Administrative username to remove : " USER_NAME
                $GROUPMOD $USER_NAME dtadmin >/dev/null
                ;;
            3)
                read -e -p $"Please enter the Monitor username to add : " USER_NAME
                if [ -n "$RHEL_OR_SLES" ]; then
                   usermod -a -G dtmon $USER_NAME 
                else
                   groupmod -A $USER_NAME dtmon
                fi
                ;;
            4)
                read -e -p $"Please enter the Monitor username to remove : " USER_NAME
                $GROUPMOD $USER_NAME dtmon >/dev/null
                ;;
            q)
                break;
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;
        esac
        read -e -p $"Press Enter to continue" CONTINUE
    done
}


configure_automount () {
    while :; do
        clear
        echo $"=== Configure File System or Block Device Replication ==="
        echo
        echo $"Menu Options:"
        echo $"1.    Configure File System Replication setup file"
        echo $"2.    Configure Block Device Replication setup file"
        echo $"3.    Manual Replication Configuration menu"
        echo $"Q.    Exit Configure File System & Block Device Replication menu"
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                add_remove_volume
                ;;
            2)
                add_remove_block_devices
                ;;
            3)
                manual_replication_config
                ;;
            q)
                break
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;

        esac
    done
}

manual_replication_config () {
    while :; do
        clear
        echo $"=== Manually Configure File System or Block Device Replication ==="
        echo
        echo $"Add a file system or block device to the replicatable list."
        echo $"   Entries added using this method will still be removed"
        echo $"   when the service is stopped or server is shutdown."
        echo
        echo $"Currently replicatable file systems & block devices:"
        if [ -f $PROC_DTFS_MOUNTS ]; then
            MOUNTED_VOLUMES=$(cat $PROC_DTFS_MOUNTS | grep "hooks:" || true)
        else
            MOUNTED_VOLUMES=
        fi
        if [ -z "$MOUNTED_VOLUMES" ]; then
            echo $"*** No replicatable file systems or block devices ***"
        else
            echo "$MOUNTED_VOLUMES"
        fi
        echo
        echo $"Menu Options:"
        echo $"1.   Manually mount DTFS on a file system (auto umounted when the service stops)"
        echo $"2.   Manually unmount a DTFS file system"
        echo $"3.   Manually attach DTLOOP to a block device (detached when the service stops)"
        echo $"4.   Manually detach DTLOOP from a block device"
        echo $"Q.   Exit Manual Replication Configuration menu"
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                #Load the kernel modules
                if ! load_dt_kernel_modules; then
                    howl "$DAEMON_BINARY_NAME drivers not loaded; replication disabled"
                fi

                # Wait for the user/kernel space communications link to come up.
                if ! MSG=$(DTRepWait 2>&1); then
                    howl "$MSG; replication disabled"
                fi

                read -e -p $"Enter the specific file system to replicate :" SPECIFIC_MOUNT_POINT
                if [ -z "$SPECIFIC_MOUNT_POINT" ]; then
                    echo $"A valid mount point must be entered."
                else
                    read -e -p $"Should access times be replicated? [y/N]:" REPATIME
                    REPATIME=$(echo $REPATIME | tr '[:upper:]' '[:lower:]')
                    if [ -n "$REPATIME" -a "y" = "$REPATIME" ]; then
                       REPATIME="repatime"
                    else
                       REPATIME="norepatime"
                    fi   
                    mount -t dtfs -o "$REPATIME" "$SPECIFIC_MOUNT_POINT" "$SPECIFIC_MOUNT_POINT"
                    if ! MSG=$(DTRegisterFS "$SPECIFIC_MOUNT_POINT" 2>&1); then
                        squawk "register of "$SPECIFIC_MOUNT_POINT" failed: ${MSG:-unknown error}"
                    fi
                fi
                ;;
            2)
                read -e -p $"Enter the specific replicated file system to unmount :" SPECIFIC_MOUNT_POINT
                if [ -z "$SPECIFIC_MOUNT_POINT" ]; then
                    echo $"A valid mount point must be entered."
                else
                    if ! MSG=$(DTUnregisterFS "$SPECIFIC_MOUNT_POINT" 2>&1); then
                        squawk "unregister of $SPECIFIC_MOUNT_POINT failed: $MSG"
                    fi

                    if ! MSG=$(umount -l -t dtfs "$SPECIFIC_MOUNT_POINT" 2>&1); then
                        squawk "unmount of replicated mount point $SPECIFIC_MOUNT_POINT failed:"
                    fi
                fi
                ;;
            3)
                #Load the kernel modules
                if ! load_dt_kernel_modules; then
                    howl "$DAEMON_BINARY_NAME drivers not loaded; replication disabled"
                fi

                # Wait for the user/kernel space communications link to come up.
                if ! MSG=$(DTRepWait 2>&1); then
                    howl "$MSG; replication disabled"
                fi

                read -e -p $"Enter the specific block device to replicate :" BLOCK_DEVICE
                if [ -z "$BLOCK_DEVICE" ]; then
                    echo $"A valid block device was not entered."
                else
                    DOIT="n"
                    DOIT_LOOP="n"
                    IS_BLOCK_VALID=$(stat -f -c "%T" "$BLOCK_DEVICE" 2>/dev/null)
                    IS_LOOP_VALID="yes"
                    if [ -z "$IS_BLOCK_VALID" ]; then
                        echo $"WARNING!" "$BLOCK_DEVICE" $"either does not exist or is not a supported block device."
                        read -e -p $"Add anyway? (y/N) " DOIT
                        DOIT=$(echo $DOIT | tr '[:upper:]' '[:lower:]')
                    fi
                    if [ -n "$IS_BLOCK_VALID" -o "$DOIT" = "y" ]; then
                        read -e -p $"Enter a loop device or nothing for the first-available: " LOOP_DEV
                        if [ -n "$LOOP_DEV" ]; then
                            IS_LOOP_VALID=$(stat -f -c "%T" $LOOP_DEV 2>/dev/null)
                        fi
                        if [ -z "$IS_LOOP_VALID" ]; then
                            echo $"WARNING!" "$LOOP_DEV" $"either does not exist or is not a supported loop device."
                            read -e -p $"Add anyway? (y/N) " DOIT_LOOP
                            DOIT_LOOP=$(echo $DOIT_LOOP | tr '[:upper:]' '[:lower:]')
                        fi
                    fi    
                    if [ -n "$IS_BLOCK_VALID" -o "$DOIT" = "y" -a \
                         -n "$IS_LOOP_VALID" -o "$DOIT_LOOP" = "y" ]; then
                        read -e -p $"Enter the file offset or nothing: " OFFSET
                        if [ -z "$OFFSET" ]; then
                           OFFSET=0
                        fi
                        read -e -p $"Enter encryption type or nothing: " ENCRYPT

                        if [ -z "$LOOP_DEV" ]; then
                           MSG=$(DTLoSetup $ENCRYPT_FLAG $OFFSET_FLAG -f $BLOCK_DEVICE 2>&1)
                       else
                           MSG=$(DTLoSetup $ENCRYPT_FLAG $OFFSET_FLAG $LOOP_DEVICE $BLOCK_DEVICE 2>&1)
                       fi
                       if [ -n "$MSG" ]; then
                           squawk "DTLOOP attach of $BLOCK_DEVICE failed: ${MSG}"
                       fi
                       if ! MSG=$(DTRegisterFS "$BLOCK_DEVICE" 2>&1); then
                           squawk "register of $BLOCK_DEVICE failed: ${MSG}"
                       fi
                    fi
                fi
                ;;
            4)
                read -e -p $"Enter the specific replicated block device point to detach :" SPECIFIC_BLOCK_DEVICE
                if [ -z "$SPECIFIC_BLOCK_DEVICE" ]; then
                    echo $"A valid mount point must be entered."
                else
                    if ! MSG=$(DTUnregisterFS "$SPECIFIC_BLOCK_DEVICE" 2>&1); then
                        squawk "unregister of $SPECIFIC_BLOCK_DEVICE failed: $MSG"
                    fi

                    for LOOP_DEV in $(ls -1 /dev/loop* 2>/dev/null); do
                        BLOCK_DEV1="($SPECIFIC_BLOCK_DEVICE),"
                        BLOCK_DEV2="$(DTLoSetup $LOOP_DEV 2>/dev/null| awk '{print $3}')"
                        if [ "$BLOCK_DEV1" = "$BLOCK_DEV2" ]; then 
                           if ! MSG=$(DTLoSetup -d "$LOOP_DEV"); then
                               sqwawk "Unable to remove loop device: $MSG"
                           fi   
                        fi
                    done
                fi
                ;;
            q)
                break
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;

        esac
    done
}

add_remove_volume () {
    # Make sure there's a file to use
    if [ ! -f "$DTFS_MOUNTS" ]; then
        touch "$DTFS_MOUNTS"
    fi
    while :; do
        clear
        echo $"=== Configure File System Replication Setup File ==="
        echo
        echo $"Maintain the DTFS mount points file, "$DTFS_MOUNTS","
        echo $"   which is processed by /etc/init.d/$SERVICE_ALIAS when the service is"
        echo $"   started and stopped during system boot or shutdown."
        echo
        echo $"File System entries in $DTFS_MOUNTS:"
        # Output details about the replicated mount points
        ENTRIES=$(cat "$DTFS_MOUNTS")
        if [ -n "$ENTRIES" ]; then
            # Parse the dtfs_mounts file for individual entries
            awk -F\  '{print $1,$2,$3}' "$DTFS_MOUNTS" | while read MOUNT_POINT UPPER REPATIME
            do
                if [ "$UPPER" = "repatime" -o "$UPPER" = "norepatime" ]; then
                   REPATIME="$UPPER"
                   UPPER=""
                fi
                if [ -z "$REPATIME" ]; then
                   REPATIME="norepatime"
                fi
                if [ -n "$MOUNT_POINT" ]; then
                    # Don't let the user get away with invalid or unmounted volumes
                    if [ "/" == "$MOUNT_POINT" -o "/boot" == "$MOUNT_POINT" ]; then
                        echo $"WARNING! '/' and /boot should not be replicated"
                    fi
                    IS_VALID=$(stat -f -c "%T" $MOUNT_POINT 2>/dev/null)
                    if [ -z "$IS_VALID" ]; then
                        echo $"WARNING! No volume mounted at $MOUNT_POINT: Mount or remove $MOUNT_POINT!"
                    else
                        IS_VOLUME=$(mount | grep -v dtfs | grep " $MOUNT_POINT ")
                        if [ -n "$IS_VOLUME" ]; then
                            mount | grep -v dtfs | grep " $MOUNT_POINT " | awk -F\  '{print $1,$3,$5}' | while read DEV_VOL MOUNT TYPE
                            do
                                echo $"$DEV_VOL mounted on $MOUNT type $TYPE option: $REPATIME"
                            done
                        else
                            echo $"dtfs mounted on $MOUNT_POINT type dtfs option: $REPATIME"
                        fi
                    fi
                fi
            done
        else
            echo $"None"
        fi
        echo
        echo $"File System entries not being replicated:"
        mount -t ext2,ext3,reiserfs | grep -v " / " | grep -v " /boot" | awk -F\  '{print $1,$3,$5}' | while read DEV_VOL MOUNT_POINT MOUNT_TYPE
        do
            ALREADY_ADDED=$(grep -w "$MOUNT_POINT" "$DTFS_MOUNTS")
            if [ -z "$ALREADY_ADDED" ]; then
                IS_ALREADY_REP=$(grep "$MOUNT_POINT" "$PROC_DTFS_MOUNTS" 2>/dev/null)
                if [ -z "$IS_ALREADY_REP" ]; then
                    echo $"$DEV_VOL mounted on $MOUNT_POINT type $MOUNT_TYPE"
                fi
            fi
        done
        echo
        echo $"Currently replicatable file systems & block devices:"
        if [ -f $PROC_DTFS_MOUNTS ]; then
            MOUNTED_VOLUMES=$(cat $PROC_DTFS_MOUNTS | grep "hooks:" || true)
        else
            MOUNTED_VOLUMES=
        fi
        if [ -z "$MOUNTED_VOLUMES" ]; then
            echo $"*** No replicatable file systems or block devices ***"
        else
            echo "$MOUNTED_VOLUMES"
        fi
        echo
        echo $"==========================================="
        echo $"Menu Options"
        echo $"1.    Add an entry to $DTFS_MOUNTS"
        echo $"2.    Remove an entry from $DTFS_MOUNTS"
        echo $"3.    Mount all entries in $DTFS_MOUNTS as DTFS"
        echo $"4.    Unmount DTFS from all entries in $DTFS_MOUNTS"
        echo $"Q.    Exit Configure File System Setup File menu"
        echo
        echo $"These must be mount points or subdirectories of"
        echo $"   ext2/ext3/reiserfs filesystems already mounted on the system."
        echo
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                read -e -p $"Enter the mount point of the volume to replicate : " VOLUME
                if [ -z "$VOLUME" ]; then
                    echo $"A valid volume must be entered."
                else
                    DOIT="n"
                    IS_VALID=$(stat -f -c "%T" "$VOLUME" | grep "ext2/ext3" || true)
		    if [ -z "$IS_VALID" ]; then #Added by @IndusaDevTeam
                        IS_VALID=$(stat -f -c "%T" "$VOLUME" | grep "reiserfs" || true)
                    fi
                    if [ "/" == "$VOLUME" -o \
                         "/boot" == "$VOLUME" ]; then
                        echo $"WARNING! '/' and /boot should not be replicated"
                        IS_VALID=""
                    fi
                    if [ -z "$IS_VALID" ]; then
                        echo $"WARNING!" "$VOLUME" $"either does not exist or is not a supported file system."
                        read -e -p $"Add anyway? (y/N) " DOIT
                        DOIT=$(echo $DOIT | tr '[:upper:]' '[:lower:]')
                    fi
                    read -e -p "Should access times be replicated? [y/N]: " REPATIME
                    REPATIME=$(echo $REPATIME | tr '[:upper:]' '[:lower:]')
                    if [ -n "$REPATIME" -a "y" = "$REPATIME" ]; then
                       REPATIME="repatime"
                    else
                       REPATIME="norepatime"
                    fi
                    if [ -n "$IS_VALID" -o "$DOIT" = "y" ]; then
                        NEW_MOUNTPOINT=$(grep -w "$VOLUME" "$DTFS_MOUNTS" || true)
                        if ! [ -z "$NEW_MOUNTPOINT" ]; then
                            echo "$VOLUME" $"is already in the replicated mount point list."
                        else
                            echo $"$VOLUME $REPATIME" >> "$DTFS_MOUNTS"
                            echo "$VOLUME" $"added to replicated mount point list."
                            echo $"If $SERVICE_DISPLAY_NAME is already running, restart to begin replicating this volume"
                            echo $"or choose option 3."
                        fi
                    fi
                fi
                ;;
            2)
                read -e -p $"Enter the mount point of the volume to remove : " VOLUME
                if [ -z "$VOLUME" ]; then
                    echo $"A valid volume must be entered."
                else
                    IS_VALID=$(grep -w "$VOLUME" "$DTFS_MOUNTS" || true)

                    if [ -z "$IS_VALID" ]; then
                        echo $"A valid volume must be entered."
                    else
                        echo $"Backing up $DTFS_MOUNTS."
                        cp -f "$DTFS_MOUNTS" "$DTFS_MOUNTS"."$BACKUP_CONF_FILE_EXT"
                        grep -wv "$VOLUME" "$DTFS_MOUNTS"."$BACKUP_CONF_FILE_EXT" > "$DTFS_MOUNTS" || true
                        echo $"$VOLUME no longer in replicated mount point list."
                        echo $"If $SERVICE_DISPLAY_NAME is currently running, restart to stop replicating this volume"
                        echo $"choose option 4 to umount all or go to the Service Start/Stop menu to unmount just one."
                    fi
                fi
                ;;
            3)
                #Load the kernel modules
                if ! load_dt_kernel_modules; then
                    howl "$DAEMON_BINARY_NAME drivers not loaded; replication disabled"
                fi

                # Wait for the user/kernel space communications link to come up.
                if ! MSG=$(DTRepWait 2>&1); then
                    howl "$MSG; replication disabled"
                fi

                mount_and_register_file_systems || :
                ;;
            4)
                unregister_and_unmount_file_systems
                ;;
            q)
                break;
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;
        esac
        read -e -p $"Press Enter to continue" CONTINUE
    done
}

add_remove_block_devices () {
    # Make sure there's a file to use
    if [ ! -f "$DTLOOP_MOUNTS" ]; then
        touch "$DTLOOP_MOUNTS"
    fi
    while :; do
        clear
        echo $"=== Configure Block Device Replication Setup File ==="
        echo
        echo $"Maintain the DTLOOP attachment file, "$DTLOOP_MOUNTS","
        echo $"   which is processed by /etc/init.d/$SERVICE_ALIAS when the service is"
        echo $"   started and stopped during system boot or shutdown."
        echo
        echo $"Block Device entries in $DTLOOP_MOUNTS:"
        # Output details about the replicated mount points
        ENTRIES=$(cat "$DTLOOP_MOUNTS")
        if [ -n "$ENTRIES" ]; then
            # Parse the dtloop file for individual entries
            while read BLOCK_DEVICE LOOP_DEVICE OFFSET ENCRYPT
            do
                if [ -n "$BLOCK_DEVICE" ]; then
                    # Don't let the user get away with invalid devices
                    if [ -z "$ENCRYPT" ]; then
                       ENCRYPT="None"
                    fi
                    if [ -z "$OFFSET" ]; then
                       OFFSET=0
                    fi
                    IS_BLOCK_VALID=$(stat -f -c "%T" $BLOCK_DEVICE 2>/dev/null)
                    IS_LOOP_VALID="yes"
                    if [ "-f" != "$LOOP_DEVICE" ]; then
                        IS_LOOP_VALID=$(stat -f -c "%T" $LOOP_DEVICE 2>/dev/null)
                    else
                        LOOP_DEVICE="first-available"
                    fi
                    if [ -z "$IS_BLOCK_VALID" ]; then
                        echo $"WARNING! No block device at $BLOCK_DEVICE: Configure or remove $BLOCK_DEVICE!"
                    elif [ -z "$IS_LOOP_VALID" ]; then
                        echo $"WARNING! No loop device at $LOOP_DEVICE: Configure or remove $LOOP_DEVICE!"
                    else
                        echo "Device: $BLOCK_DEVICE Loop Device: $LOOP_DEVICE Encryption: $ENCRYPT Offset: $OFFSET"
                    fi
                fi
            done < $DTLOOP_MOUNTS
        else
            echo $"None"
        fi
        echo
        echo $"Currently replicatable file systems & block devices:"
        if [ -f $PROC_DTFS_MOUNTS ]; then
            MOUNTED_VOLUMES=$(cat $PROC_DTFS_MOUNTS | grep "hooks:" || true)
        else
            MOUNTED_VOLUMES=
        fi
        if [ -z "$MOUNTED_VOLUMES" ]; then
            echo $"*** No replicatable file systems or block devices ***"
        else
            echo "$MOUNTED_VOLUMES"
        fi
        echo
        echo $"==========================================="
        echo $"Menu Options"
        echo $"1.    Add an entry to $DTLOOP_MOUNTS"
        echo $"2.    Remove an entry from $DTLOOP_MOUNTS"
        echo $"3.    Attach all entries in $DTLOOP_MOUNTS to a loop device"
        echo $"4.    Detach loop devices from all entries in $DTLOOP_MOUNTS"
        echo $"5.    List block devices on this system (except swap and LVM physical partitions)"
        echo $"Q.    Exit Configure Block Device Setup File menu"
        echo
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                read -e -p $"Enter the block device to replicate : " VOLUME
                if [ -z "$VOLUME" ]; then
                    echo $"A valid block device was not entered."
                else
                    DOIT="n"
                    DOIT_LOOP="n"
                    IS_BLOCK_VALID=$(stat -f -c "%T" "$VOLUME" 2>/dev/null)
                    IS_LOOP_VALID="yes"
                    if [ -z "$IS_BLOCK_VALID" ]; then
                        echo $"WARNING!" "$VOLUME" $"either does not exist or is not a supported block device."
                        read -e -p $"Add anyway? (y/N) " DOIT
                        DOIT=$(echo $DOIT | tr '[:upper:]' '[:lower:]')
                    fi
                    if [ -n "$IS_BLOCK_VALID" -o "$DOIT" = "y" ]; then
                        read -e -p $"Enter a loop device or nothing for the first-available: " LOOP_DEV
                        if [ -n "$LOOP_DEV" ]; then
                            IS_LOOP_VALID=$(stat -f -c "%T" $LOOP_DEV 2>/dev/null)
                        else
                            LOOP_DEV="-f"
                        fi
                        if [ -z "$IS_LOOP_VALID" ]; then
                            echo $"WARNING!" "$LOOP_DEV" $"either does not exist or is not a supported loop device."
                            read -e -p $"Add anyway? (y/N) " DOIT_LOOP
                            DOIT_LOOP=$(echo $DOIT_LOOP | tr '[:upper:]' '[:lower:]')
                        fi
                    fi    
                    if [ -n "$IS_BLOCK_VALID" -o "$DOIT" = "y" -a \
                         -n "$IS_LOOP_VALID" -o "$DOIT_LOOP" = "y" ]; then
                        read -e -p $"Enter the file offset or nothing: " OFFSET
                        if [ -z "$OFFSET" ]; then
                           OFFSET=0
                        fi
                        read -e -p $"Enter encryption type or nothing: " ENCRYPT

                        NEW_MOUNTPOINT=$(grep -w "$VOLUME" "$DTLOOP_MOUNTS" || true)
                        if ! [ -z "$NEW_MOUNTPOINT" ]; then
                            echo "$VOLUME" $"is already in the replicated mount point list."
                        else
                            echo $"$VOLUME $LOOP_DEV $OFFSET $ENCRYPT" >> "$DTLOOP_MOUNTS"
                            echo "$VOLUME" $"added to replicated device list."
                            echo $"If $SERVICE_DISPLAY_NAME is already running, restart to begin replicating this volume"
                            echo $"or choose option 3."
                        fi
                    fi
                fi
                ;;
            2)
                read -e -p $"Enter the block device to remove : " VOLUME
                if [ -z "$VOLUME" ]; then
                    echo $"A valid block device was not entered."
                else
                    IS_VALID=$(grep -w "$VOLUME" "$DTLOOP_MOUNTS" || true)

                    if [ -z "$IS_VALID" ]; then
                        echo $"A valid block device must be entered."
                    else
                        echo $"Backing up $DTLOOP_MOUNTS."
                        cp -f "$DTLOOP_MOUNTS" "$DTLOOP_MOUNTS"."$BACKUP_CONF_FILE_EXT"
                        grep -wv "$VOLUME" "$DTLOOP_MOUNTS"."$BACKUP_CONF_FILE_EXT" > "$DTLOOP_MOUNTS" || true
                        echo $"$VOLUME no longer in replicated block device list."
                        echo $"If $SERVICE_DISPLAY_NAME is currently running, restart to stop replicating this device."
                        echo $"choose option 4 to disable all or go to the Service Start/Stop menu to disable just one."
                    fi
                fi
                ;;
            3)
                #Load the kernel modules
                if ! load_dt_kernel_modules; then
                    howl "$DAEMON_BINARY_NAME drivers not loaded; replication disabled"
                fi

                # Wait for the user/kernel space communications link to come up.
                if ! MSG=$(DTRepWait 2>&1); then
                    howl "$MSG; replication disabled"
                fi

                attach_and_register_block_devices || :
                ;;
            4)
                unregister_and_detach_block_devices
                ;;
            5)
                #Dan's block device listing program
                clear
                #cat /proc/partitions
		DTPartitionInfo -c DISPLAY_NAME PARTITION_SIZE FILE_SYSTEM MOUNT_POINT --show-all --exclude-swap --exlude-lvm-physical
                ;;
            q)
                break;
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;
        esac
        read -e -p $"Press Enter to continue" CONTINUE
    done
}

start_stop_dblt () {
    while :; do
        clear
        echo $"=== Service Start/Stop ==="
        echo
        echo $"=== Current $SERVICE_DISPLAY_NAME state ==="
        STATUS=$(/sbin/service $SERVICE_ALIAS status || true)
        echo "$STATUS"
        echo
        echo $"Kernel module load state:"
        DTFS_LOADED=$(/sbin/lsmod | grep dtfs | grep -v exportfs || true)
        DTREP_LOADED=$(/sbin/lsmod | grep dtrep | grep -v dtfs || true)
        if [ -z "$DTFS_LOADED" ]; then
            echo $"dtfs module not loaded"
        else
            echo "$DTFS_LOADED"
        fi
        if [ -z "$DTREP_LOADED" ]; then
            echo $"dtrep module not loaded"
        else
            echo "$DTREP_LOADED"
        fi
	DTLOOP_LOADED=$(/sbin/lsmod | grep dtloop | grep -v dtfs | grep -v "^loop" || true)
        if [ -z "$DTLOOP_LOADED" ]; then
            echo $"dtloop module not loaded"
        else
            echo "$DTLOOP_LOADED"
        fi
        if [ -z "$DTREP_LOADED" \
             -o -z "$DTFS_LOADED" \
             -o -z "$DTLOOP_LOADED" \
           ]; then
            echo $"*** dtfs/dtrep modules will be loaded when $SERVICE_DISPLAY_NAME starts ***"
        fi
        echo
        echo $"Currently replicatable file systems & block devices:"
        if [ -f $PROC_DTFS_MOUNTS ]; then
            MOUNTED_VOLUMES=$(cat $PROC_DTFS_MOUNTS | grep "hooks:" || true)
        else
            MOUNTED_VOLUMES=
        fi
        if [ -z "$MOUNTED_VOLUMES" ]; then
            echo $"*** No replicatable file systems or block devices ***"
        else
            echo "$MOUNTED_VOLUMES"
        fi
        echo
        echo $"File Systems & Block Devices replicatable when $SERVICE_DISPLAY_NAME starts: "
        if [ -f "$DTFS_MOUNTS" ]; then
            AUTO_MOUNTS=$(awk -F\  '{print $1}' "$DTFS_MOUNTS")
        else
            AUTO_MOUNTS=
        fi
        if [ -f "$DTLOOP_MOUNTS" ]; then
            AUTO_ATTACH=$(awk -F\  '{print "Block Device: "$1}' "$DTLOOP_MOUNTS")
        else
            AUTO_ATTACH=
        fi
 
        if [ -z "$AUTO_MOUNTS" -a -z "$AUTO_ATTACH" ]; then
            echo $"*** Go to the Setup Tasks menu to configure the ***"
            echo $"*** auto-mounting replicated mount points. (#3) ***"
        else
            if [ "$AUTO_MOUNTS" ]; then
                echo "$AUTO_MOUNTS"
            fi
            if [ "$AUTO_ATTACH" ]; then
                echo "$AUTO_ATTACH"
            fi
            echo
        fi
        echo
        echo $"================================="
        echo $"Menu Options:"
        echo $"1.   Start $SERVICE_DISPLAY_NAME and process driver config"
        echo $"2.   Stop $SERVICE_DISPLAY_NAME but preserve driver config"
        echo $"3.   Restart service but preserve driver config"
        echo $"4.   Restart service and reset driver config"
        echo $"5.   Stop the running service and teardown driver config"
        echo $"6.   Go to Replication Configuration menu"
        echo $"Q.   Exit Service Start/Stop Menu"
        echo
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                /sbin/service $SERVICE_ALIAS start
                ;;
            2)
                /sbin/service $SERVICE_ALIAS stop
                ;;
            3)
                /sbin/service $SERVICE_ALIAS restart
                ;;
            4)
                /sbin/service $SERVICE_ALIAS reload
                ;;
            5)
                /sbin/service $SERVICE_ALIAS halt
                ;;
            6)
                configure_automount
                ;;
            q)
                break;
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;
        esac
    done
}

view_logs () {
    DTLOG_DIR=$(grep "^LogDir" $CONF_FILE | awk -F\  '{print $2}')
    DTLOG_FILE=$(grep "^LogFile" $CONF_FILE | awk -F\  '{print $2}' | tr '[:upper:]' '[:lower:]')
    while :; do
        clear
        echo $"=== View $SERVICE_DISPLAY_NAME log file output ==="
        echo
        echo $"Menu Options:"
        echo $"1.   View $DTLOG_DIR/$DTLOG_FILE*.dtl in less"
        echo $"2.   Follow the output of latest $DTLOG_FILE"
        echo $"3.   View /var/log/messages in less"
        echo $"4.   Follow the output of /var/log/messages"
        echo $"Q.   Exit View $SERVICE_DISPLAY_NAME log file output Menu"
        echo
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                if [ -d "$DTLOG_DIR" ]; then
                    STORE_PWD=$(pwd)
                    cd "$DTLOG_DIR"
                    less $(ls -r -C "$DTLOG_FILE"*.dtl)
                    cd "$STORE_PWD"
                else
                    echo
                    read -e -p $"$DTLOG_DIR not present. Press Enter to continue" ENTER_KEY
                fi
                ;;
            2)
                if [ -d "$DTLOG_DIR" ]; then
                    STORE_PWD=$(pwd)
                    cd "$DTLOG_DIR"
                    echo $"Monitoring latest $DTLOG_FILE.  Type CTRL-C to quit."
                    echo
                    tail -n 20 -f $(ls -C "$DTLOG_FILE"*.dtl | tail -1)&
                    TAILPID_2=$!

                    # Set up signal handler.
                    trap "kill $TAILPID_2" INT PIPE TERM

                    wait

                    # Restore default signal handler.
                    trap >&- 2>&-


                    cd "$STORE_PWD"
                    read -p "Press Enter to return to menu: "
                    clear
                else
                    echo
                    read -e -p $"$DTLOG_DIR not present. Press Enter to continue" ENTER_KEY
                fi
                ;;
            3)
                if [ -f /var/log/messages ]; then
                    less /var/log/messages
                else
                    echo
                    read -e -p $"/var/log/messages not present. Press Enter to continue" ENTER_KEY
                fi
                ;;
            4)
                if [ -f /var/log/messages ]; then
                    echo $"Monitoring /var/log/messages.  Type CTRL-C to quit."
                    echo
                    tail -n 20 -f /var/log/messages &
                    TAILPID_4=$!

                    # Set up signal handler.
                    trap "kill $TAILPID_4" INT PIPE TERM

                    wait

                    # Restore default signal handler.
                    trap >&- 2>&-

                    read -p "Press Enter to return to menu: "
                    clear
                else
                    echo
                    read -e -p $"/var/log/messages not present. Press Enter to continue" ENTER_KEY
                fi
                ;;
            q)
                break
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;
        esac
    done
}

view_docs () {
# First retrieve any defaults that were persisted
    if [ -f $CONFIG_DIR/DTSetup.conf ]; then
       . $CONFIG_DIR/DTSetup.conf
    fi

# Search for a valid viewer, or inform the user one needs installed
    DEFAULT_PDF_VIEWER="[Please install a PDF viewer]"
# Check the persisted one
    if [ -n "$PDF_VIEWER" ]; then
       PDF_VIEWER=$(which $PDF_VIEWER 2>/dev/null)
    fi
    if [ -z "$PDF_VIEWER" ]; then
       PDF_VIEWER=$(which kpdf 2>/dev/null)
    fi
    if [ -z "$PDF_VIEWER" ]; then
       PDF_VIEWER=$(which evince 2>/dev/null)
    fi
    if [ -z "$PDF_VIEWER" ]; then
       PDF_VIEWER=$(which gpdf 2>/dev/null)
    fi
# Cleanup
    if [ -n "$PDF_VIEWER" ]; then
       DEFAULT_PDF_VIEWER=$(basename $PDF_VIEWER)
    fi

# Search for a valid viewer, or inform the user one needs installed
    DEFAULT_HTML_VIEWER="[Please install an HTML viewer]"
# Check the persisted one
    if [ -n "$HTML_VIEWER" ]; then
       HTML_VIEWER=$(which $HTML_VIEWER 2>/dev/null)
    fi
    if [ -z "$HTML_VIEWER" ]; then
       HTML_VIEWER=$(which firefox 2>/dev/null)
    fi
    if [ -z "$HTML_VIEWER" ]; then
       HTML_VIEWER=$(which lynx 2>/dev/null)
    fi
    if [ -z "$HTML_VIEWER" ]; then
       HTML_VIEWER=$(which elinks 2>/dev/null)
    fi
# Cleanup
    if [ -n "$HTML_VIEWER" ]; then
       DEFAULT_HTML_VIEWER=$(basename $HTML_VIEWER)
    fi

# Search for a valid viewer, or inform the user one needs installed
    DEFAULT_TXT_VIEWER="[Please install a TXT viewer]"
# Check the persisted one
    if [ -z "$TXT_VIEWER" ]; then
       TXT_VIEWER=$(which $TXT_VIEWER 2>/dev/null)
    fi
    if [ -z "$TXT_VIEWER" ]; then
       TXT_VIEWER=$(which less 2>/dev/null)
    fi
    if [ -z "$TXT_VIEWER" ]; then
       TXT_VIEWER=$(which more 2>/dev/null)
    fi
# Cleanup
    if [ -n "$TXT_VIEWER" ]; then
       DEFAULT_TXT_VIEWER=$(basename $TXT_VIEWER)
    fi

    HTML_VIEWER=$DEFAULT_HTML_VIEWER
    PDF_VIEWER=$DEFAULT_PDF_VIEWER
    TXT_VIEWER=$DEFAULT_TXT_VIEWER
    DTDOC_DIR=/usr/share/doc/${INSTALL_SUBDIR}/
    while :; do
        clear
        echo $"=== View $SERVICE_DISPLAY_NAME documentation ==="
        echo
        echo $"Menu Options:"
        echo $"1.   View ReadMe HTML with $HTML_VIEWER"
        echo $"2.   View Scripting Guide PDF with $PDF_VIEWER"
        echo $"3.   View Users Guide PDF with $PDF_VIEWER"
        echo $"4.   View Evaluation Guide PDF with $PDF_VIEWER"
        echo $"5.   View Premium Maintenance Agreement PDF with $PDF_VIEWER"
        echo $"6.   View Enterprise Maintenance Agreement PDF with $PDF_VIEWER"
        echo $"7.   View End User License Agreement TXT with $TXT_VIEWER"
        echo $"8.   View dtfs/dtrep module license TXT with $TXT_VIEWER"
        echo $"9.   Change a document viewer"
        echo $"Q.   Exit View $SERVICE_DISPLAY_NAME documentation Menu"
        echo
        echo $"If an appropriate viewer is not installed, these will not work."
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        if [ -d "$DTDOC_DIR" ]; then
            STORE_PWD=$(pwd)
            cd "$DTDOC_DIR"
            case "$MENU_OPTION" in
                1)
                    $HTML_VIEWER "$DTDOC_DIR"/"$DTBRAND_READMEHTML"
                    ;;
                2)
                    $PDF_VIEWER "$DTDOC_DIR"/"$DTBRAND_SCRIPTING_GUIDE"
                    ;;
                3)
                    $PDF_VIEWER "$DTDOC_DIR"/"$DTBRAND_USERS_GUIDE"
                    ;;
                4)
                    $PDF_VIEWER "$DTDOC_DIR"/"$DTBRAND_EVALUATION_GUIDE"
                    ;;
                5)
                    $PDF_VIEWER "$DTDOC_DIR/Premium Maintenance Agreement.pdf"
                    ;;
                6)
                    $PDF_VIEWER "$DTDOC_DIR/Enterprise Maintenance Agreement.pdf"
                    ;;
                7)
                    $TXT_VIEWER "$DTDOC_DIR"/license.txt
                    ;;
                8)
                    $TXT_VIEWER "$DTDOC_DIR"/dtfs_dtrep_kernel_module_license.txt
                    ;;
                9)
                    mv -f $CONFIG_DIR/DTSetup.conf $CONFIG_DIR/DTSetup.conf.$BACKUP_CONF_FILE_EXT 2>/dev/null
                    VALID_PATH=""
                    while :; do
                       read -e -p $"HTML viewer [$HTML_VIEWER] : " NEW_HTML_VIEWER
                       if [ "$NEW_HTML_VIEWER" -a "$NEW_HTML_VIEWER" != "$DEFAULT_HTML_VIEWER" ]; then
                          if [ -n $(which $NEW_HTML_VIEWER 2>/dev/null) ]; then
                             HTML_VIEWER=$NEW_HTML_VIEWER
                             echo "HTML_VIEWER=$HTML_VIEWER" >> $CONFIG_DIR/DTSetup.conf
                          else
                             echo $"Invalid HTML viewer: "$NEW_HTML_VIEWER
                             continue;
                          fi
                       fi
                       break
                    done
                    while :; do
                       read -e -p $"PDF viewer [$PDF_VIEWER] : " NEW_PDF_VIEWER
                       if [ "$NEW_PDF_VIEWER" -a "$NEW_PDF_VIEWER" != "$DEFAULT_PDF_VIEWER" ]; then
                          if [ -n $(which $NEW_PDF_VIEWER 2>/dev/null) ]; then
                             PDF_VIEWER=$NEW_PDF_VIEWER
                             echo "PDF_VIEWER=$PDF_VIEWER" >> $CONFIG_DIR/DTSetup.conf
                          else
                             echo $"Invalid PDF viewer: "$NEW_PDF_VIEWER
                             continue;
                          fi
                       fi
                       break
                    done
                    while :; do
                       read -e -p $"TXT viewer [$TXT_VIEWER] : " NEW_TXT_VIEWER
                       if [ "$NEW_TXT_VIEWER" -a "$NEW_TXT_VIEWER" != "$DEFAULT_TXT_VIEWER" ]; then
                          if [ -n $(which $NEW_TXT_VIEWER 2>/dev/null) ]; then
                             TXT_VIEWER=$NEW_TXT_VIEWER
                             echo "TXT_VIEWER=$TXT_VIEWER" >> $CONFIG_DIR/DTSetup.conf
                          else
                             echo $"Invalid TXT viewer: "$NEW_TXT_VIEWER
                             continue;
                          fi
                       fi
                       break
                    done
                    ;;
                q)
                    break
                    ;;
                --)
                    break
                    ;;
                *)
                    echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                    ;;
            esac
            cd "$STORE_PWD"
        else
            echo
            read -e -p $"$DTDOC_DIR not present. Press Enter to continue" ENTER_KEY
        fi
    done
}

collect_dtinfo () {
    /usr/bin/DTInfo.sh
    read -e -p $"Press Enter to continue. " ENTER
}

portstatus_iptables () {
    if [ -r "$CONF_FILE" ]; then

        if ! grep -qw UNetPort "$CONF_FILE"; then
            UNETPORT=1500
        else
            UNETPORT=$(grep -w UNetPort "$CONF_FILE" | awk -F\  '{print $2}')
        fi

        if ! grep -qw NetPort "$CONF_FILE"; then
            NETPORT=1500
        else
            NETPORT=$(grep -w NetPort "$CONF_FILE" | awk -F\  '{print $2}')
        fi

        if ! grep -qw DirUNetPort "$CONF_FILE"; then
            DIRUNETPORT=1505
        else
            DIRUNETPORT=$(grep -w DirUNetPort "$CONF_FILE" | awk -F\  '{print $2}')
        fi

        if ! grep -qw StatsPort "$CONF_FILE"; then
            STATSPORT=1506
        else
            STATSPORT=$(grep -w StatsPort "$CONF_FILE" | awk -F\  '{print $2}')
        fi
    else
        UNETPORT=1500
        NETPORT=1500
        DIRUNETPORT=1505
        STATSPORT=1506
    fi

    if ! grep -qw "\-A RH-Firewall-1-INPUT \-p udp \-m state \--state NEW \-m udp \--dport $UNETPORT \-j ACCEPT" /etc/sysconfig/iptables; then
        UNETPORTSTATUS="Not explicitly opened"
    else
        UNETPORTSTATUS="Open"
    fi

    if ! grep -qw "\-A RH-Firewall-1-INPUT \-p tcp \-m state \--state NEW \-m tcp \--dport $NETPORT \-j ACCEPT" /etc/sysconfig/iptables; then
        NETPORTSTATUS="Not explicitly opened"
    else
        NETPORTSTATUS="Open"
    fi

    if ! grep -qw "\-A RH-Firewall-1-INPUT \-p udp \-m state \--state NEW \-m udp \--dport $DIRUNETPORT \-j ACCEPT" /etc/sysconfig/iptables; then
        DIRUNETPORTSTATUS="Not explicitly opened"
    else
        DIRUNETPORTSTATUS="Open"
    fi

    if ! grep -qw "\-A RH-Firewall-1-INPUT \-p tcp \-m state \--state NEW \-m tcp \--dport $STATSPORT \-j ACCEPT" /etc/sysconfig/iptables; then
        STATSPORTSTATUS="Not explicitly opened"
    else
        STATSPORTSTATUS="Open"
    fi

    if ! grep -qw "\-A RH-Firewall-1-INPUT \-j REJECT \--reject-with icmp-host-prohibited" /etc/sysconfig/iptables; then
        DEFAULTREJECT=0
    else
        DEFAULTREJECT=1
    fi
}

portstatusprint_iptables () {
    portstatus_iptables
    echo $"=== Current $SERVICE_DISPLAY_NAME port status ==="
    echo $"UNetPort($UNETPORT): $UNETPORTSTATUS"
    echo $"NetPort($NETPORT): $NETPORTSTATUS"
    echo $"DirUNetPort($DIRUNETPORT): $DIRUNETPORTSTATUS"
    echo $"StatsPort($STATSPORT): $STATSPORTSTATUS"
    echo
}

portopen_iptables () {
    # Attempt to remove rule first to prevent duplicates
    /sbin/iptables -D RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport $UNETPORT -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport $DIRUNETPORT -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport $NETPORT -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport $STATSPORT -j ACCEPT > /dev/null 2>&1

    # Attempt to remove default ports as well
    /sbin/iptables -D RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport 1500 -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport 1505 -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 1500 -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 1506 -j ACCEPT > /dev/null 2>&1

    # Temporarily remove REJECT rule so our ACCEPTS will occur
    # before it
    /sbin/iptables -D RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1

    # Add rules allowing connections to DT ports
    /sbin/iptables -A RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport $UNETPORT -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -A RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport $DIRUNETPORT -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport $NETPORT -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport $STATSPORT -j ACCEPT > /dev/null 2>&1

    if [ $DEFAULTREJECT -eq 1 ]; then
        # Re-add REJECT rule
        /sbin/iptables -A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
        
        # Save the rules
        /sbin/service iptables save
        read -e -p $"Press Enter to continue" ENTER
    else
        echo $"Unable to open firewall ports - check your firewall configuration."
        read -e -p $"Press Enter to continue" ENTER
    fi
}

portclose_iptables () {
    # Remove rules
    /sbin/iptables -D RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport $UNETPORT -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport $DIRUNETPORT -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport $NETPORT -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport $STATSPORT -j ACCEPT > /dev/null 2>&1

    # Attempt to remove default ports as well
    /sbin/iptables -D RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport 1500 -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p udp -m state --state NEW -m udp --dport 1505 -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 1500 -j ACCEPT > /dev/null 2>&1
    /sbin/iptables -D RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 1506 -j ACCEPT > /dev/null 2>&1

    # Save the rules
    /sbin/service iptables save
    read -e -p $"Press Enter to continue" ENTER
}
    
configure_iptables () {
    if [ -n "$INTERACTIVE" ]; then
    while :; do
        clear
        portstatusprint_iptables
        echo $"=== Configure iptables for $SERVICE_DISPLAY_NAME ==="
        echo
        echo $"Menu Options:"
        echo $"1.    Open $SERVICE_DISPLAY_NAME ports in iptables"
        echo $"2.    Close $SERVICE_DISPLAY_NAME ports in iptables"
        echo $"Q.    Exit Configure iptables for $SERVICE_DISPLAY_NAME Menu"
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')

        case "$MENU_OPTION" in
            1)
                portopen_iptables
                ;;
            2)
                portclose_iptables
                ;;
            q)
                break
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;

        esac
    done
    else
      portstatus_iptables
      case "$FIREWALLNI" in
            1)
		portopen_iptables
		portstatusprint_iptables
		;;
	
	    2)
		portclose_iptables
		portstatusprint_iptables
		;;

	    *)
	        echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized firewall option" 
	        usage
	        exit 0
	        ;;
      esac      
    fi
}

bool_to_str () {
    if [ "$1" = "1" ]; then
        echo "true"
    else
        echo "false"
    fi
}

is_boolean () {
    if [ "$1" = "0" ] || [ "$1" = "1" ]; then
        return 0
    else
        return 1
    fi
}

is_setting_set () {
    VAR="$1"
    ANSWER=
    case "$VAR" in
        enable_statistics)
            test -n "$ENABLE_STATISTICS" && ANSWER=yes
            ;;
        ioControlEnable)
            test -n "$IO_CONTROL_ENABLE" && ANSWER=yes
            ;;
        ioControlForce)
            test -n "$IO_CONTROL_FORCE" && ANSWER=yes
            ;;
        ioControlInterval)
            test -n "$IO_CONTROL_INTERVAL" && ANSWER=yes
            ;;
        ioControlStartLevel)
            test -n "$IO_CONTROL_START_LEVEL" && ANSWER=yes
            ;;
        ioControlStopLevel)
            test -n "$IO_CONTROL_STOP_LEVEL" && ANSWER=yes
            ;;
        memory_limit)
            test -n "$MEMORY_LIMIT" && ANSWER=yes
            ;;
        write_chunk_size)
            test -n "$WRITE_CHUNK_SIZE" && ANSWER=yes
            ;;
        *)
            grumble "is_setting_set(): unrecognized setting \"$VAR\""
            ;;
    esac
    if [ -n "$ANSWER" ]; then
        return 0
    else
        return 1
    fi
}

make_setting_default () {
    VAR="$1"
    case "$VAR" in
        enable_statistics)
            ENABLE_STATISTICS=0
            ;;
        ioControlEnable)
            IO_CONTROL_ENABLE=1
            ;;
        ioControlForce)
            IO_CONTROL_FORCE=0
            ;;
        ioControlInterval)
            IO_CONTROL_INTERVAL=10
            ;;
        ioControlStartLevel)
            IO_CONTROL_START_LEVEL=2
            ;;
        ioControlStopLevel)
            IO_CONTROL_STOP_LEVEL=0
            ;;
        memory_limit)
            MEMORY_LIMIT=$(( 64 * 1024 * 1024 )) # 64 MB
            ;;
        write_chunk_size)
            WRITE_CHUNK_SIZE=$(( 64 * 1024 )) # 64 kB
            ;;
        *)
            grumble "make_setting_default(): unrecognized setting \"$VAR\""
            ;;
    esac
}

validate_setting () {
    VAR="$1"
    VALUE="$2"
    case "$VAR" in
        enable_statistics)
            if is_boolean "$VAR"; then
                ENABLE_STATISTICS="$VALUE"
            else
                return 1
            fi
            ;;
        ioControlEnable)
            if is_boolean "$VAR"; then
                IO_CONTROL_ENABLE="$VALUE"
            else
                return 1
            fi
            ;;
        ioControlForce)
            if is_boolean "$VAR"; then
                IO_CONTROL_FORCE="$VALUE"
            else
                return 1
            fi
            ;;
        ioControlInterval)
            if ! [ "$VALUE" -eq "$VALUE" ] 2>/dev/null; then
                return 1
            elif [ "$VALUE" -lt 10 ]; then
                return 1
            elif [ "$VALUE" -gt $IO_CONTROL_INTERVAL_MAX ]; then
                return 1
            fi
            ;;
        ioControlStartLevel)
            if ! [ "$VALUE" -eq "$VALUE" ] 2>/dev/null; then
                return 1
            elif [ "$VALUE" -lt 1 ]; then
                return 1
            elif [ "$VALUE" -gt 100 ]; then
                return 1
            fi
            if [ "$VALUE" -le "$IO_CONTROL_STOP_LEVEL" ] 2>/dev/null; then
               return 1
            fi
            ;;
        ioControlStopLevel)
            if ! [ "$VALUE" -eq "$VALUE" ] 2>/dev/null; then
                return 1
            elif [ "$VALUE" -lt 0 ]; then
                return 1
            elif [ "$VALUE" -gt 100 ]; then
                return 1
            fi
            if [ "$VALUE" -ge "$IO_CONTROL_START_LEVEL" ] 2>/dev/null; then
               return 1
            fi
            ;;
        memory_limit)
            if ! [ "$VALUE" -eq "$VALUE" ] 2>/dev/null; then
                return 1
            elif [ "$VALUE" -lt $MEMORY_LIMIT_MIN ]; then
                return 1
            elif [ "$VALUE" -gt $MEMORY_LIMIT_MAX ]; then
                return 1
            fi
            ;;
        write_chunk_size)
            if ! [ "$VALUE" -eq "$VALUE" ] 2>/dev/null; then
                return 1
            elif [ "$VALUE" -lt 0 ]; then
                return 1
            elif [ "$VALUE" -gt $WRITE_CHUNK_SIZE_MAX ]; then
                return 1
            fi
            ;;
        *)
            grumble "validate_setting(): unrecognized setting \"$VAR\""
            ;;
    esac
    return 0
}

get_current_setting () {
    VAR="$1"

    if ! [ -r "$PROC_DTREP_CONTROL/$VAR" ]; then
        grumble "get_current_setting(): $PROC_DTREP_CONTROL/$VAR does not" \
            "exist or is not readable"
        return 1
    fi

    CURRENT_VALUE=$(cat "$PROC_DTREP_CONTROL/$VAR")
    if [ -n "$DTREP_LOADED" ]; then
        case "$VAR" in
            enable_statistics)
                : ${ENABLE_STATISTICS:="$CURRENT_VALUE"}
                ;;
            ioControlEnable)
                : ${IO_CONTROL_ENABLE:="$CURRENT_VALUE"}
                ;;
            ioControlForce)
                : ${IO_CONTROL_FORCE:="$CURRENT_VALUE"}
                ;;
            ioControlInterval)
                : ${IO_CONTROL_INTERVAL:="$CURRENT_VALUE"}
                ;;
            ioControlStartLevel)
                : ${IO_CONTROL_START_LEVEL:="$CURRENT_VALUE"}
                ;;
            ioControlStopLevel)
                : ${IO_CONTROL_STOP_LEVEL:="$CURRENT_VALUE"}
                ;;
            memory_limit)
                : ${MEMORY_LIMIT:="$CURRENT_VALUE"}
                ;;
            write_chunk_size)
                : ${WRITE_CHUNK_SIZE:="$CURRENT_VALUE"}
                ;;
            *)
                grumble "get_current_setting(): unrecognized setting \"$VAR\""
                ;;
        esac
    fi

    return 0
}

toggle_boolean () {
    VAR="$1"
    PROBLEM=
    case "$VAR" in
        enable_statistics)
            ENABLE_STATISTICS=$(( ! $ENABLE_STATISTICS ))
            VALUE=$ENABLE_STATISTICS
            SETTING_TEXT=$"DTRepStatistics"
            ;;
        ioControlEnable)
            IO_CONTROL_ENABLE=$(( ! $IO_CONTROL_ENABLE ))
            VALUE=$IO_CONTROL_ENABLE
            SETTING_TEXT=$"Adaptive Throttling"
            ;;
        ioControlForce)
            IO_CONTROL_FORCE=$(( ! $IO_CONTROL_FORCE ))
            VALUE=$IO_CONTROL_FORCE
            SETTING_TEXT=$"Forced Adaptive Throttling"
            ;;
        *)
            grumble "toggle_boolean(): unrecognized setting \"$VAR\""
            PROBLEM=yes
            ;;
    esac

    if [ -z "$PROBLEM" ]; then
        CONTROL_FILE="$PROC_DTREP_CONTROL/$VAR"
        if [ -r "$CONTROL_FILE" ]; then
            echo $VALUE > "$CONTROL_FILE"
            printf $"%s set to %s.\n" "$SETTING_TEXT" $(bool_to_str $VALUE)
        else
            echo $"This change will take effect the next time $SERVICE_DISPLAY_NAME is started."
        fi
    fi
}

adjust_setting () {
    VAR="$1"
    VALUE="$2"
    PROBLEM=
    case "$VAR" in
        enable_statistics|ioControlEnable|ioControlForce)
            grumble "adjust_setting(): should call toggle_boolean for setting \"$VAR\""
            PROBLEM=
            ;;
        ioControlInterval)
            IO_CONTROL_INTERVAL="$VALUE"
            MSG=$"Throttling Delay set to %d milliseconds.\n"
            ;;
        ioControlStartLevel)
            IO_CONTROL_START_LEVEL="$VALUE"
            MSG=$"Throttling Start Level set to %d%%.\n"
            ;;
        ioControlStopLevel)
            IO_CONTROL_STOP_LEVEL="$VALUE"
            MSG=$"Throttling Stop Level set to %d%%.\n"
            ;;
        memory_limit)
            MEMORY_LIMIT="$VALUE"
            MSG=$"Kernel memory usage set to %d bytes.\n"
            ;;
        write_chunk_size)
            WRITE_CHUNK_SIZE="$VALUE"
            MSG=$"Maximum Write Buffer Size set to %d bytes.\n"
            ;;
        *)
            grumble "adjust_setting(): unrecognized setting \"$VAR\""
            PROBLEM=
            ;;
    esac

    if [ -z "$PROBLEM" ]; then
        CONTROL_FILE="$PROC_DTREP_CONTROL/$VAR"
        if [ -w "$CONTROL_FILE" ]; then
            echo $VALUE > "$CONTROL_FILE"
            printf "$MSG" "$VALUE"
        else
            echo $"$CONTROL_FILE does not exist or is not writable."
            echo $"This change will take effect the next time $SERVICE_DISPLAY_NAME is started."
        fi
    fi
}

rewrite_settings () {
    SEDEXPR=
    VAR_LIST=
    # Read variable name/value pairs from the argument list.
    while [ -n "$1" ] && [ -n "$2" ]; do
        VAR="$1"
        VALUE="$2"
        PROBLEM=
        case "$VAR" in
            # Nothing to do for legal values except accept them.
            enable_statistics)
                ;;
            ioControlEnable)
                ;;
            ioControlForce)
                ;;
            ioControlInterval)
                ;;
            ioControlStartLevel)
                ;;
            ioControlStopLevel)
                ;;
            memory_limit)
                ;;
            write_chunk_size)
                ;;
            *)
                grumble "rewrite_settings(): unrecognized setting \"$VAR\""
                VAR=
                VALUE=
                ;;
        esac
        if [ -n "$VAR" ] && [ -n "$VALUE" ]; then
            SEDEXPR="${SEDEXPR:+$SEDEXPR }\"-e s/$VAR.*/$VAR $VALUE/\""
            VAR_LIST=${VAR_LIST:+$VAR_LIST }$VAR
        fi
        shift 2
    done
    # Create the settings file if it doesn't exist.
    if ! [ -e "$DTREP_SETTINGS" ]; then
        > "$DTREP_SETTINGS"
    fi
    if [ -n "$SEDEXPR" ]; then
        # Populate the file with any variables we're setting but which aren't
        # already present in the file.
        for VAR in $VAR_LIST; do
            if ! grep -qw "$VAR" "$DTREP_SETTINGS"; then
                echo "$VAR" >> "$DTREP_SETTINGS"
            fi
        done

        # Write out the new settings.
        echo $"Backing up $DTREP_SETTINGS and rewriting with new value."
        BACKUP_EXPR=-i."$BACKUP_CONF_FILE_EXT"
        eval sed "$BACKUP_EXPR" $SEDEXPR "$DTREP_SETTINGS"
    fi
}

configure_performance () {
    # Ensure settings variables start without values.
    ENABLE_STATISTICS=
    IO_CONTROL_ENABLE=
    IO_CONTROL_FORCE=
    IO_CONTROL_INTERVAL=
    IO_CONTROL_START_LEVEL=
    IO_CONTROL_STOP_LEVEL=
    MEMORY_LIMIT=
    WRITE_CHUNK_SIZE=

    # /proc/dtrep/control must exist if we're going to use it.
    DTREP_LOADED=
    if [ -d "$PROC_DTREP_CONTROL" ]; then
        DTREP_LOADED=yes
    else
        grumble "$PROC_DTREP_CONTROL nonexistent or not a directory"
        echo $"The dtrep kernel module is not loaded."
        echo $"Performance settings will not be activated until dtrep has been loaded."
        read -e -p $"Press Enter to continue. " ENTER
    fi

    if [ -r "$DTREP_SETTINGS" ]; then
        while read VAR VALUE; do
            if validate_setting "${VAR##*/}" "$VALUE"; then
                adjust_setting "${VAR##*/}" "$VALUE"
            fi
        done < "$DTREP_SETTINGS"
    fi

    # If a setting is unset, grab the current setting from /proc/dtrep/control
    # if it is available, otherwise set to the default value.
    for VAR in enable_statistics \
        ioControlEnable \
        ioControlForce \
        ioControlInterval \
        ioControlStartLevel \
        ioControlStopLevel \
        memory_limit \
        write_chunk_size; do
        is_setting_set "$VAR" || get_current_setting "$VAR" \
            || make_setting_default "$VAR"
    done

    while :; do
        clear
        echo $"=== Configure $SERVICE_DISPLAY_NAME driver performance ==="
        echo
        echo $"Current performance settings:"
        echo
        # Output details about the current settings.
# ---------------------------------------*---------------------------------------*
# Enable DTRep Statistics:          false Enable Adaptive Throttling:        false
# Force Adaptive Throttling Active: false Throttling Delay (milliseconds): xyyyzzz
# Throttling Start Level (percentage): nn Throttling Stop Level (percentage):   nn
# Kernel Memory used (bytes): wwxxxyyyzzz Maximum Write Buffer Size: vwwwxxxyyyzzz
# ---------------------------------------*---------------------------------------*
        # Translators will need to ensure that this stuff fits into 2 colums of
        # 40 characters each.
        printf $"Enable DTRep Statistics: %14s " \
            $(bool_to_str "$ENABLE_STATISTICS")
        printf $"Enable Adaptive Throttling: %12s\n" \
            $(bool_to_str "$IO_CONTROL_ENABLE")
        printf $"Force Adaptive Throttling Active: %5s " \
            $(bool_to_str "$IO_CONTROL_FORCE")
        printf $"Throttling Delay (milliseconds): %7d\n" "$IO_CONTROL_INTERVAL"
        printf $"Throttling Start Level (percentage): %2d " \
            "$IO_CONTROL_START_LEVEL"
        printf $"Throttling Stop Level (percentage): %4d\n" \
            "$IO_CONTROL_STOP_LEVEL"
        printf $"Kernel Memory Used (bytes): %11d " "$MEMORY_LIMIT"
        printf $"Maximum Write Buffer Size: %13d\n" "$WRITE_CHUNK_SIZE"
        echo
        echo $"==========================================="
        echo $"Menu Options"
        echo $"1.    Toggle DTRepStatistics (*)"
        echo $"2.    Toggle Adaptive Throttling (*)"
        echo $"3.    Toggle Forced Adaptive Throttling (*)"
        echo $"4.    Set Throttling Delay (in milliseconds)"
        echo $"5.    Set Throttling Start Level (percentage)"
        echo $"6.    Set Throttling Stop Level (percentage)"
        echo $"7.    Set Kernel Memory Used (bytes)"
        echo $"8.    Set Maximum Write Buffer Size"
        echo $"Q.    Exit Configure $SERVICE_DISPLAY_NAME driver performance menu"
        echo
        echo "(*) indicates options that may decrease performance when enabled"
        echo
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                toggle_boolean enable_statistics
                rewrite_settings enable_statistics "$ENABLE_STATISTICS"
                ;;
            2)
                toggle_boolean ioControlEnable
                rewrite_settings ioControlEnable "$IO_CONTROL_ENABLE"
                ;;
            3)
                toggle_boolean ioControlForce
                # If we're forcing adaptive throttling on, we also need to
                # enable it.  Turn that setting off, then toggle it, so we get
                # the side effects of toggle_boolean().
                if [ $IO_CONTROL_FORCE -eq 1 ]; then
                    IO_CONTROL_ENABLE=0
                    # Hide our kludge from the user.
                    toggle_boolean ioControlEnable > /dev/null
                fi
                rewrite_settings ioControlEnable "$IO_CONTROL_ENABLE" \
                    ioControlForce "$IO_CONTROL_FORCE"
                ;;
            4)
                clear
                echo $"Set the Throttling Delay"
                echo "================================================================================"
                echo
                echo $"Press Enter to keep the current Throttling Delay."
                get_current_setting ioControlInterval
                read -e -p $"Please enter the Throttling Delay (in milliseconds) ["$IO_CONTROL_INTERVAL"]: " ENTRY
                if [ -z "$ENTRY" ]; then
                    ENTRY="$IO_CONTROL_INTERVAL"
                fi

                if validate_setting ioControlInterval "$ENTRY"; then
                    adjust_setting ioControlInterval "$ENTRY"
                    rewrite_settings ioControlInterval "$ENTRY"
                else
                    echo $"The Throttling Delay must be a positive integer between 10 and $IO_CONTROL_INTERVAL_MAX."
                fi
                ;;
            5)
                clear
                echo $"Set the Throttling Start Level"
                echo "================================================================================"
                echo
                echo $"Press Enter to keep the current Start Level."
                get_current_setting ioControlStartLevel
                read -e -p $"Please enter the Throttling Start Level (percentage) ["$IO_CONTROL_START_LEVEL"]: " ENTRY
                if [ -z "$ENTRY" ]; then
                    ENTRY="$IO_CONTROL_START_LEVEL"
                fi

                if validate_setting ioControlStartLevel "$ENTRY"; then
                    adjust_setting ioControlStartLevel "$ENTRY"
                    rewrite_settings ioControlStartLevel "$ENTRY"
                else
                    echo $"The Throttling Start Level must be an integer between 1 and 100 and greater than the Stop Level."
                fi
                ;;
            6)
                clear
                echo $"Set the Throttling Stop Level"
                echo "================================================================================"
                echo
                echo $"Press Enter to keep the current Stop Level."
                get_current_setting ioControlStopLevel
                read -e -p $"Please enter the Throttling Stop Level (percentage) ["$IO_CONTROL_STOP_LEVEL"]: " ENTRY
                if [ -z "$ENTRY" ]; then
                    ENTRY="$IO_CONTROL_STOP_LEVEL"
                fi

                if validate_setting ioControlStopLevel "$ENTRY"; then
                    adjust_setting ioControlStopLevel "$ENTRY"
                    rewrite_settings ioControlStopLevel "$ENTRY"
                else
                    echo $"The Throttling Stop Level must be an integer between 0 and 100 and less than the Start Level."
                fi
                ;;
            7)
                clear
                echo $"Set the amount of Kernel Memory Used"
                echo "================================================================================"
                echo
                echo $"Press Enter to keep the current memory limit."
                get_current_setting memory_limit
                read -e -p $"Please enter the amount of Kernel Memory Used (bytes) ["$MEMORY_LIMIT"]: " ENTRY
                if [ -z "$ENTRY" ]; then
                    ENTRY="$MEMORY_LIMIT"
                fi

                if validate_setting memory_limit "$ENTRY"; then
                    adjust_setting memory_limit "$ENTRY"
                    rewrite_settings memory_limit "$ENTRY"
                else
                    echo $"The Kernel Memory Used must be a positive integer between $MEMORY_LIMIT_MIN and $MEMORY_LIMIT_MAX."
                fi
                ;;
            8)
                clear
                echo $"Set the Maximum Write Buffer Size"
                echo "================================================================================"
                echo
                echo $"Press Enter to keep the current maximum write buffer size."
                get_current_setting write_chunk_size
                read -e -p $"Please enter the Maximum Write Buffer Size ["$WRITE_CHUNK_SIZE"]: " ENTRY
                if [ -z "$ENTRY" ]; then
                    ENTRY="$WRITE_CHUNK_SIZE"
                fi

                if validate_setting write_chunk_size "$ENTRY"; then
                    adjust_setting write_chunk_size "$ENTRY"
                    rewrite_settings write_chunk_size "$ENTRY"
                else
                    echo $"The Maximum Write Buffer Size must be a positive integer between 0 and $WRITE_CHUNK_SIZE_MAX."
                fi
                ;;
            q)
                break;
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;
        esac
        read -e -p $"Press Enter to continue" CONTINUE
    done
}

setup_dt () {
    while :; do
        clear
        echo $"=== $SERVICE_DISPLAY_NAME Setup ==="
        echo
        echo $"Menu Options:"
        echo $"1.    Set activation code"
        echo $"2.    Add/Remove users to $SERVICE_DISPLAY_NAME groups"
        echo $"3.    Configure File System or Block Device Replication"
        echo $"4.    Configure iptables for $SERVICE_DISPLAY_NAME"
        echo $"5.    Edit $SERVICE_DISPLAY_NAME config file (optional)"
        echo $"6.    Configure $SERVICE_DISPLAY_NAME driver performance (optional)"
        echo $"Q.    Exit $SERVICE_DISPLAY_NAME Setup Menu"
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                insert_key
                read -e -p $"Press Enter to continue" USER_NAME
                ;;
            2)
                add_remove_user
                ;;
            3)
                configure_automount
                ;;
            4)  
                configure_iptables
                ;;
            5)
                clear
                EDITOR_FOUND=
                if [ -x /usr/bin/nano ]; then
                    EDITOR_FOUND=yes
                    /usr/bin/nano -S "$CONF_FILE"
                else if [ -x /usr/bin/vim ]; then
                    EDITOR_FOUND=yes
                    /usr/bin/vim "$CONF_FILE"
                fi
                fi
                if [ -z "$EDITOR_FOUND" ]; then
                   echo $"Nano and vim not found.  Edit $CONF_FILE elsewhere."
                fi
                ;;
            6)
                configure_performance
                ;;
            q)
                break
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;

        esac
    done
}

troubleshoot_dt () {
    while :; do
        clear
        echo $"=== $SERVICE_DISPLAY_NAME Troubleshooting ==="
        echo
        echo $"Menu Options:"
        echo $"1.    View log files"
        echo $"2.    Collect and package diagnostic info"
        echo $"3.    View user documentation"
        echo $"Q.    Exit $SERVICE_DISPLAY_NAME Troubleshooting Menu"
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                view_logs
                ;;
            2)
                collect_dtinfo
                ;;
            3)
                view_docs
                ;;
            q)
                break
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;

        esac
    done
}



menu () {
    while :; do
        clear
        echo $"=== $SCRIPT_NAME Main Menu ==="
        echo
        echo $"Menu Options:"
        echo $"1.    Setup tasks"
        echo $"2.    Start/Stop $SERVICE_DISPLAY_NAME daemon"
        echo $"3.    Start User Interface (DTCL -i)"
        echo $"4.    Documentation/Troubleshooting tasks" 
        echo $"Q.    Quit $SCRIPT_NAME"
        echo
        read -e -p $"Please choose a menu option : " MENU_OPTION
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                setup_dt
                ;;
            2)
                start_stop_dblt
                ;;
            3)
                clear
                DTCL -i
                ;;
            4)
                troubleshoot_dt
                ;;
            q)
                clear
                exit
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;
        esac
    done
}

# XXX: Embedding variable names might not work with translatable strings.
usage () {
# Undocument -E option per legal.
#    -E YES      Run non-interactively; YES argument indicates that the user
#                accepts the ${EULA_NAME} End User License Agreement
    echo <<EOF $"Usage: $SCRIPT_NAME [OPTION ...]
Configure a $SERVICE_DISPLAY_NAME installation.
By default, $SCRIPT_NAME will bring up an interactive menu.

Options:
    -c FILE     Use FILE as the configuration file.
                (default: \"$DEFAULT_CONF_FILE\")
    -h          Display this message and exit.
    -k KEY      Run non-interactively; interpret KEY as the activation key
                and rewrite the configuration file accordingly.
    -O          Run non-interactively; perform the firewall port open operation.
    -C          Run non-interactively; perform the firewall port close opearation.

For further information, use the command \"man DTSetup\" to view the manual
page.
"
EOF
}
INTERACTIVE="YES"
if [ $# -gt 0 ]; then
    while getopts "hc:E:k:OC" OPTION; do  # Added one more option i.e 'O'and 'C' by @IndusaDevTeam
        case "$OPTION" in
            c)
                CONF_FILE="$OPTARG"
                ;;
            k)
                ACTIVATION_KEY="$OPTARG"
                INTERACTIVE=
                ;;
            E)
                if [ ! -f "$EULA_FILE" ]; then
                    ACCEPT_EULA="$OPTARG"
                    INTERACTIVE=
                else
                    squawk "${EULA_NAME} End User License Agreement" \
                           "already accepted on this system"
                    exit 0
                fi
                ;;
            O)  
                FIREWALLNI="1"
                INTERACTIVE=
                ;;
            C)
                FIREWALLNI="2"
                INTERACTIVE=
                ;;
            h)
                usage
                exit 0
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$1\""
                usage >&2
                exit 1
        esac
    done
fi

# Must run as root.
if [ "$(id -u)" != "0" ]; then
    echo "$SCRIPT_NAME:" $"error:" \
         $"superuser privileges required to run this program" >&2
    exit 2
fi

#Ensure that the DT runlevels are setup
if [ ! -e /etc/rc5.d/S23DT -o \
     ! -e /etc/rc6.d/K76DT -o \
     ! -e /etc/rc3.d/S23DT ]; then
   /sbin/chkconfig --add DT
fi

if [ ! -f "$EULA_FILE" ]; then
    # scriptable
    eula_accept
fi

if [ -n "$ACTIVATION_KEY" ]; then
    # scriptable
    insert_key
fi

if [ -n "$FIREWALLNI" ]; then
    # scriptable
    configure_iptables
fi

if [ -n "$INTERACTIVE" ]; then
    # Interactive
    menu
fi

exit 0

