#!/bin/bash
#
# DT Configuration Scriptlet

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

# Get branding-related environment
# Bug#1757 Changed by @IndusaDevTeam
source /etc/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}"
DTREPSETGENERATOR="/usr/share/${INSTALL_SUBDIR}/DTRepsetGenerator.sh"
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"
ADDON_CODES="AddOnCodes"
NODE_LOCKED_LICENSE_KEY="NodeLockedLicenseKey"
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_DELAY_MAX=1000 # 1 second
IO_CONTROL_INTERVAL_MAX=100 # 10th of a second
MEMORY_LIMIT_MIN=$(( 4 * 1024 )) # 4 kB
MEMORY_LIMIT_MAX=$(( 1024 * 1024 * 1024 )) # 1 GB
WRITE_CHUNK_SIZE_MAX=$(( 1024 * 1024 )) # 1 MB
NO_ACCESS_MSG="insufficient user access level"

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

# SCR00227599 : Added by @IndusaDevTeam
# Generates the 24 chars key in correct format after removing
# an extra hyphens, white-spaces and multiple entries from the code
generate_key_in_correct_format () {
   export ENTRY
   ${CONFIG_DIR}/bin/DTInit.sh -I #Bug#1757 Changed by @IndusaDevTeam
   unset ENTRY
}

insert_key () {
    if [ -n "$INTERACTIVE" ]; then
        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

    # Added by @IndusaDevTeam
    # SCR00227599 : Generates the 24 chars key in correct format
    generate_key_in_correct_format
}

## AddOnCodes option in the Menu list
insert_addoncodes () {
    if [ -n "$INTERACTIVE" ]; then
        echo
        read -e -p $"Please enter the $SERVICE_DISPLAY_NAME add on code: " AOCENTRY
    else
        AOCENTRY="$ADDON_KEY"
    fi
    if [ -n "$AOCENTRY" ]; then
        # Backup the conf file
        if [ -e "$CONF_FILE" ]; then
            BACKUP_FILE="${CONF_FILE}.${BACKUP_CONF_FILE_EXT}-$(get_date)"
            cp "$CONF_FILE" "$BACKUP_FILE"
        fi

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

activation_code_menu () {
    STATUS=$(/etc/init.d/$SERVICE_ALIAS status | grep pid || true)
    while :; do
        clear
        echo $"=== Set Activation Code Menu  ==="
        echo
        echo $"$SERVICE_DISPLAY_NAME activation codes are needed to authorize"
        echo $"   use of the service's various capabilities and features."
        echo $"   - Activation codes can be evaluation, machine specific or site wide."
#        echo $"   - AddOn codes authenticate node-locked servers or additional features."
        echo $"   Current codes have 24 characters not including '-'s, older codes have 16."
        echo
        # Output the current set of admins and monitors
        ACTIVATIONCODE=$(grep $ACTIVATION_CODE $CONF_FILE 2>/dev/null | awk -F\  '{print $2}')
#        ADDONCODES=$(grep $ADDON_CODES $CONF_FILE 2>/dev/null | head -1 | awk -F\  '{print $2}')
#        NODELOCKEDLICENSEKEY=$(grep $NODE_LOCKED_LICENSE_KEY $CONF_FILE 2>/dev/null | awk -F\  '{print $2}')
        if [ -n "$ACTIVATIONCODE" ]; then echo "$ACTIVATION_CODE $ACTIVATIONCODE"; fi
#        if [ -n "$ADDONCODES" ]; then grep $ADDON_CODES $CONF_FILE 2>/dev/null; fi
#        if [ -n "$NODELOCKEDLICENSEKEY" ]; then echo "$NODE_LOCKED_LICENSE_KEY $NODELOCKEDLICENSEKEY"; fi
        echo
        echo $"==================================="
        echo $"Menu Options"
        echo $"1.    Set Activation Code in $CONF_FILE"
#        echo $"2.    Set an Add-On Code in $CONF_FILE"
#        if [ "$STATUS" ]; then
#            echo $"3.    Set Activation Code through service (dtadmin password required)"
#            echo $"4.    Set an AddOn Code through service (dtadmin password required)"
#        fi
        echo $"Q.    Exit the Set Activation Code 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)
                 insert_key 
                 read -e -p $"Press Enter to continue" CONTINUE
                 ;;
#            2)
#                 insert_addoncodes
#                 read -e -p $"Press Enter to continue" CONTINUE
#                 ;; 
#            3)
#                read -e -p $"Enter the name of a user in the dtadmin group: " DTADMIN
#                read -e -s -p $"Enter the password of the user: " DTADMIN_PASS
#                echo
#                echo $"Press Enter to keep the current activation code."
#                echo $"Do not enter dashes ('-') as part of 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
#                HOSTNAME=$(hostname)
#                /usr/bin/DTCL login ${HOSTNAME} ${DTADMIN} ${DTADMIN_PASS}; set ${ACTIVATION_CODE}="$ENTRY" ${HOSTNAME};
#                ;;
#            4)
#                read -e -p "Enter the name of a user in the dtadmin group: " DTADMIN
#                read -e -s -p "Enter the password of the user: " DTADMIN_PASS
#                echo
#                echo $"Do not enter dashes ('-') as part of code."
#                read -e -p $"Please enter the $SERVICE_DISPLAY_NAME add-on code: " ENTRY
#                HOSTNAME=$(hostname)
#                /usr/bin/DTCL login ${HOSTNAME} ${DTADMIN} ${DTADMIN_PASS}; set ${ADDON_CODES}="$ENTRY" ${HOSTNAME};
#                ;;
            q)
                break;
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;
        esac
    done
}

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
                        if [ -f "/usr/share/doc/${INSTALL_SUBDIR}/license.txt" ]; then
                          less -Ps"[Press space to continue, 'q' when done.]" /usr/share/doc/${INSTALL_SUBDIR}/license.txt
                        else
                          zcat "/usr/share/doc/${INSTALL_SUBDIR}/license.txt.gz" | less -Ps"[Press space to continue, 'q' when done.]"
                        fi
                    elif [ -x /bin/more ]; then
                        if [ -f "/usr/share/doc/${INSTALL_SUBDIR}/license.txt" ]; then
                          more -d /usr/share/doc/${INSTALL_SUBDIR}/license.txt
                        else
                          zcat "/usr/share/doc/${INSTALL_SUBDIR}/license.txt.gz" | more -d
                        fi
                    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 "$USER_NAME" ]; then
                   if [ -n "$RHEL_OR_SLES" ]; then
                      usermod -a -G dtadmin $USER_NAME
                   else
                      groupmod -A $USER_NAME dtadmin
                   fi
                fi
                ;;
            2)
                read -e -p $"Please enter the Administrative username to remove : " USER_NAME
                if [ -n "$USER_NAME" ]; then
                   $GROUPMOD $USER_NAME dtadmin >/dev/null
                fi
                ;;
            3)
                read -e -p $"Please enter the Monitor username to add : " USER_NAME
                if [ -n "$USER_NAME" ]; then
                   if [ -n "$RHEL_OR_SLES" ]; then
                      usermod -a -G dtmon $USER_NAME 
                   else
                      groupmod -A $USER_NAME dtmon
                   fi
                fi
                ;;
            4)
                read -e -p $"Please enter the Monitor username to remove : " USER_NAME
                if [ -n "$USER_NAME" ]; then
                   $GROUPMOD $USER_NAME dtmon >/dev/null
                fi
                ;;
            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 $"4.    Full Server 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
                ;;
            4)
                full_server_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
            MNT_VOLUMES=$(echo "${MOUNTED_VOLUMES//"\040"/ }") #SCR00233118 Changed by @IndusaDevTeam
            MNT_VOLUMES=$(echo "${MNT_VOLUMES//"\134"/\\}") #SCR00233118 Changed by @IndusaDevTeam
            echo "$MNT_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 "$SERVICE_DISPLAY_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 -t dtfs "$SPECIFIC_MOUNT_POINT" 2>&1); then #SCR 233237 Changed by @IndusaDevTeam
                        squawk "unmount of replicated mount point $SPECIFIC_MOUNT_POINT failed:"
                    fi
                fi
                ;;
            3)
                #Load the kernel modules
                if ! load_dt_kernel_modules; then
                    howl "$SERVICE_DISPLAY_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
}

print_dtfs_mounts()
{
    echo $"File System entries in $DTFS_MOUNTS:"
    # Output details about the replicated mount points
    DTFS_MOUNT_ENTRIES=$(cat "$DTFS_MOUNTS" 2>/dev/null)
    if [ -n "$DTFS_MOUNT_ENTRIES" ]; then
        # Parse the dtfs_mounts file for individual entries
        while read MOUNT_POINT UPPER REPATIME #SCR237963 Changed by @IndusaDevTeam
        do
            if [ "$UPPER" = "repatime" -o "$UPPER" = "norepatime" ]; then
               REPATIME="$UPPER"
               UPPER=""
            fi
            if [ -z "$REPATIME" ]; then
               REPATIME="norepatime"
            fi
            if [ -n "$MOUNT_POINT" ]; then
                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 -w "$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"
                            break
                        done
                    else
                        echo $"dtfs mounted on $MOUNT_POINT type dtfs option: $REPATIME"
                    fi
                fi
            fi
        done <"$DTFS_MOUNTS"
    else
        echo $"None"
    fi
}

print_proc_dtfs_mounts () {
    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
        MNT_VOLUMES=$(echo "${MOUNTED_VOLUMES//"\040"/ }") #SCR00233118 Changed by @IndusaDevTeam
        MNT_VOLUMES=$(echo "${MNT_VOLUMES//"\134"/\\}") #SCR00233118 Changed by @IndusaDevTeam
        echo "$MNT_VOLUMES"
    fi
}

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
        print_dtfs_mounts
        echo
        echo $"File System entries not being replicated:"
        mount -t ext2,ext3,ext4,reiserfs,xfs | 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
        print_proc_dtfs_mounts
        echo
        echo $"==========================================="
        echo $"Menu Options"
        echo $"1.    Add an entry to $DTFS_MOUNTS"
        echo $"2.    Remove/Umount entries in $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/ext4/reiserfs/xfs 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_ENT
                VOLUME_ENT="$(echo $VOLUME_ENT | sed 's/\"//g')" # Remove "s
                VOLUME="$(echo $VOLUME_ENT | sed 's/\\/\\\\/g')" # Replace \ with /
                VOLUME="$(echo $VOLUME_ENT | sed 's/\/$//g')" # Trim trailing /
                VOLUME="$(echo $VOLUME | sed 's/\ /\\ /g')" # Change spaces to \space
                DUPLICATE=$(grep -w "$VOLUME" "$DTFS_MOUNTS") #SCR00245272 : stop making duplicate mount point entry
                if [ -z "$VOLUME" ]; then
                    echo $"A valid volume must be entered."
                else
                    if [ "$DUPLICATE" != "" ]; then #SCR00245272 : stop making duplicate mount point entry
                        echo $"Warning : Volume $VOLUME is already added as a mount point."
                    else
                        DOIT="n"
                        VOLUME_PRT="$(echo $VOLUME | sed 's/\\//g')" #SCR00237963 Added by @IndusaDevTeam
                        IS_VALID=$(stat -f -c "%T" "$VOLUME_PRT" 2>/dev/null | grep "ext2/ext3" || true)
                        if [ -z "$IS_VALID" ]; then #Added by @IndusaDevTeam
                            IS_VALID=$(stat -f -c "%T" "$VOLUME_PRT" 2>/dev/null | grep "reiserfs" || true) #SCR00228804 Changed by @IndusaDevTeam
                        fi
                        if [ -z "$IS_VALID" ]; then #Added by @IndusaDevTeam
                            IS_VALID=$(stat -f -c "%T" "$VOLUME_PRT" 2>/dev/null | grep "ext4" || true)
                        fi
                        if [ -z "$IS_VALID" ]; then #Added by @IndusaDevTeam
                            IS_VALID=$(stat -f -c "%T" "$VOLUME_PRT" 2>/dev/null | grep "xfs" || true) 
                        fi
                        if [ -z "$IS_VALID" ]; then
                            echo $"WARNING!" "$VOLUME_PRT" $"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
                        if [ -n "$IS_VALID" -o "y" = "$DOIT" ]; then #SCR00231288 Changed by @IndusaDevTeam
                            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
                            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."
                            fi
                            if pidof DT >/dev/null; then
                               read -e -p $"Should all entries be mounted now? [y/N] : " DOMOUNT
                               DOMOUNT=$(echo $DOMOUNT | tr '[:upper:]' '[:lower:]')
                               if [ "$DOMOUNT" = "y" -o "$DOMOUNT" = "yes" ]; then
                                   mount_and_register_file_systems || :
                               fi
                            else # Bug 2521 Added by @IndusaDevTeam
                               echo $"The volume will be mounted when $SERVICE_DISPLAY_NAME is started"
                               echo $"or choose option 3 to mount later."
                            fi
                        fi
                    fi
                fi
                ;;
            2)
                if [ -z "$DTFS_MOUNT_ENTRIES" ]; then
                    continue
                fi
                read -e -p $"Enter the mount point of the volume to remove or type 'ALL': " VOLUME
                VOLUME="$(echo $VOLUME | sed 's/\"//g')" #SCR00233118 Added by @IndusaDevTeam
                if [ -z "$VOLUME" ]; then
                    echo $"A valid volume must be entered."
                else
                    IS_VALID="ALL"
                    if [ "$VOLUME" != "ALL" ]; then
                        VOLUME=$(echo "${VOLUME}" | sed "s/\/*$//")
                        while read MNTPT JUNK; #SCR00233118 Added by @IndusaDevTeam
                        do
                           MNTPT=$(echo "${MNTPT}" | sed "s/\/*$//")
                           if [ "$VOLUME" = "$MNTPT" ]; then
                               IS_VALID="$MNTPT"
                               break
                           else
                               IS_VALID=
                           fi
                        done <"$DTFS_MOUNTS"
                    fi

                    if [ -z "$IS_VALID" ]; then
                        echo $"A valid volume must be entered."
                    else
                        read -e -p $"Should dtfs be unmounted first? [y/N] : " UNMOUNT
                        UNMOUNT=$(echo $UNMOUNT | tr '[:upper:]' '[:lower:]')
                        if [ "$UNMOUNT" = "y" -o "$UNMOUNT" = "yes" ]; then
                            if [ "$VOLUME" = "ALL" ]; then
                                unregister_and_unmount_file_systems
                            else
                                if ! MSG=$(DTUnregisterFS "$VOLUME" 2>&1); then
                                    squawk "unregister of $VOLUME failed: $MSG"
                                fi

                                if ! MSG=$(umount -t dtfs "$VOLUME" 2>&1); then #SCR 233237 Changed by @IndusaDevTeam
                                    squawk "unmount of replicated mount point $VOLUME failed:"
                                fi
                            fi
                        fi
                        echo $"Backing up $DTFS_MOUNTS."
                        cp -f "$DTFS_MOUNTS" "$DTFS_MOUNTS"."$BACKUP_CONF_FILE_EXT"
                        if [ "$VOLUME" = "ALL" ]; then
                            if grep -q "^/$" $DTFS_MOUNTS; then
                                echo "/" >$DTFS_MOUNTS
                                echo $"Keeping / in replicated mount point list."
                            else
                                > $DTFS_MOUNTS
                                echo $"No volumes in replicated mount point list."
                            fi
                        else
                            > $DTFS_MOUNTS
                            while read LOWER UPPER JUNK; #SCR00233118 Added by @IndusaDevTeam
                            do
                               LOWER=$(echo "${LOWER}" | sed "s/\/*$//")
                               if [ "$VOLUME" != "$LOWER" ]; then
                                    LOWER="$(echo $LOWER | sed 's/\\/\\\\/g')"
                                    LOWER="$(echo $LOWER | sed 's/\ /\\ /g')"
                                    echo "$LOWER $UPPER $JUNK" >> "$DTFS_MOUNTS"
                               fi
                            done <"$DTFS_MOUNTS"."$BACKUP_CONF_FILE_EXT"
                        fi
                    fi
                fi
                ;;
            3)
                #Load the kernel modules
                if ! load_dt_kernel_modules; then
                    howl "$SERVICE_DISPLAY_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
        DTLOOP_MOUNT_ENTRIES=$(cat "$DTLOOP_MOUNTS")
        if [ -n "$DTLOOP_MOUNT_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/Detach entries in $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)
                if [ -z "$DTLOOP_MOUNT_ENTRIES" ]; then
                    continue
                fi
                read -e -p $"Enter the block device to remove or type 'ALL': " VOLUME
                if [ -z "$VOLUME" ]; then
                    echo $"A valid block device was not entered."
                else
                    IS_VALID="ALL"
                    if [ "$VOLUME" != "ALL" ]; then
                        IS_VALID=$(grep -w "$VOLUME " "$DTLOOP_MOUNTS" || true)
                    fi

                    if [ -z "$IS_VALID" ]; then
                        echo $"A valid block device must be entered."
                    else
                        read -e -p "Should dtloop be detached first? [y/N] : " DETACH
                        DETACH=$(echo $DETACH | tr '[:upper:]' '[:lower:]')
                        if [ "$DETACH" = "y" -o "$DETACH" = "yes" ]; then
                            if [ "$VOLUME" = "ALL" ]; then
                                unregister_and_detach_block_devices
                            else
                                if ! MSG=$(DTUnregisterFS "$VOLUME" 2>&1); then
                                    squawk "unregister of $VOLUME failed: $MSG"
                                fi

                                for LOOP_DEV in $(ls -1 /dev/loop* 2>/dev/null); do
                                    BLOCK_DEV1="($VOLUME),"
                                    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
                        fi
                        echo $"Backing up $DTLOOP_MOUNTS."
                        cp -f "$DTLOOP_MOUNTS" "$DTLOOP_MOUNTS"."$BACKUP_CONF_FILE_EXT"
                        if [ "$VOLUME" = "ALL" ]; then
                            > $DTLOOP_MOUNTS
                            echo $"No block devices in replicated device list."
                        else
                            grep -wv "$VOLUME " "$DTLOOP_MOUNTS"."$BACKUP_CONF_FILE_EXT" > "$DTLOOP_MOUNTS" || true
                            echo $"$VOLUME no longer in replicated block device list."
                        fi
                    fi
                fi
                ;;
            3)
                #Load the kernel modules
                if ! load_dt_kernel_modules; then
                    howl "$SERVICE_DISPLAY_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
}

verify_service_access() {
    local SERVER=$1
    local TRYAGAIN
    local DT_ACCESS=$(/usr/bin/DTCL "source \"${SERVER}\";" | grep "$NO_ACCESS_MSG" 2>/dev/null)
    local DT_STATUS=$(/usr/bin/DTCL "source \"${SERVER}\";" | tee /dev/stderr | grep "$source" 2>/dev/null)
    if [ -n "$DT_ACCESS" ]; then
        while [ -n "$DT_STATUS" -a "$TRYAGAIN" != "n" ]; do
            TRYAGAIN="n"
            read -e -p $"Enter the name of a user in the dtadmin group: " DTADMIN
            read -e -s -p $"Enter the password of the user (password will be hidden): " DTADMIN_PASS
            echo
            echo $"Testing username and password"
            SERVER=$(hostname)
            DTCL "login \"${SERVER}\" \"${DTADMIN}\" \"${DTADMIN_PASS}\";"
            DT_ACCESS=$(DTCL "source \"${SERVER}\";" | grep "$NO_ACCESS_MSG" 2>/dev/null)
            DT_STATUS=$(DTCL "source \"${SERVER}\";" | tee /dev/stderr | grep "$source" 2>/dev/null)
            if [ -n "$DT_STATUS" ]; then
                read -e -p $"Failure accessing server, try again? (y/N): " TRYAGAIN
                if [ -z "$TRYAGAIN" ]; then TRYAGAIN="n"; fi
                TRYAGAIN=$(echo $TRYAGAIN | tr '[:upper:]' '[:lower:]')
            fi
        done
    fi
    if [ -z "$DT_ACCESS" -a -n "$DT_STATUS" ]; then
       echo "Please configure a valid $SERVICE_DISPLAY_NAME activation code."
    fi
    if [ -n "$DT_STATUS" ]; then
        return 1;
    else
        return 0;
    fi
}

full_server_replication_config () {
    local REPSET_RSP
    local REMOVE_RSP
    while :; do
        clear
        echo $"=== Configure Full Server File System Replication ==="
        echo $" Add or remove full server protection configuration"
        echo $"   - Configures root file system replication on system boot"
        echo $"   - Configures mounted file systems in $DTFS_MOUNTS"
        echo $"   - Creates a replication set if ${SERVICE_DISPLAY_NAME} is running."
        echo $" A reboot will be required to set/clear root replication"
        echo $"========================================================"
        echo $"  === Full server replication configuration status ==="
        ${DTREPSETGENERATOR} -s
        echo
        print_dtfs_mounts
        echo
        print_proc_dtfs_mounts
        echo
        echo $"===================================================="
        echo $"Menu Options:"
        echo $"1.   Add Full Server Protection"
        echo $"2.   Remove Full Server Protection"
        echo $"3.   Configure $DTFS_MOUNTS manually"
        echo $"4.   View replication set contents"
        echo $"Q.   Exit Full Server Replication Configuration menu"
        read -e -p $"Please choose a menu option : " MENU_OPTION
        echo
        MENU_OPTION=$(echo $MENU_OPTION | tr '[:upper:]' '[:lower:]')
        case "$MENU_OPTION" in
            1)
                DTADMIN="none"
                DTADMIN_PASS="none"
                if [ -n "$(/etc/init.d/${DTBRAND_SERVICE_ALIAS} status | grep -w "running" 2>/dev/null || true)" ]; then
                    echo $"${SERVICE_DISPLAY_NAME} is loaded. If the activation code is valid, then"
                    echo $" a full server replication set can be generated. Dtadmin credentials are"
                    echo $" required. This step can be done later in the Replication Console wizard."
                    echo
                    read -e -p $"Should the replication set be generated at this time? [y/N] " REPSET_RSP
                    REPSET_RSP=$(echo $REPSET_RSP | tr '[:upper:]' '[:lower:]')
                fi
                echo "Configuring full server protection"
                load_dt_kernel_modules # Load the drivers once, for side-effect of completing any outstanding driver installation steps
                ${DTREPSETGENERATOR} -a
                if [ -n "$REPSET_RSP" -a "$REPSET_RSP" = "y" ]; then
                    if ! verify_service_access $(hostname); then
                       echo $"Service access could not be established, replication set configuration aborted."
                    fi
                fi
                ${DTREPSETGENERATOR} \
                    -u "$DTADMIN" -p "$DTADMIN_PASS" \
                    -f /usr/share/${INSTALL_SUBDIR}/SRO.repset \
                    -g > ${CONFIG_DIR}/SRO.dtcl
                echo
                if [ -n "$REPSET_RSP" -a "$REPSET_RSP" = "y" ]; then
                    echo $"Generating the replication set."
                    echo $"If errors occur, check the credentials or try using the Replication Console."
                    /usr/bin/DTCL -f ${CONFIG_DIR}/SRO.dtcl
                fi
                echo
                echo $"A system reboot may be necessary to start full server protection"
                read -e -p "Press Enter to continue" ENTER
                if [ -e "${CONFIG_DIR}/SRO.dtcl" ]; then
                    sed -e "/login/D" ${CONFIG_DIR}/SRO.dtcl > ${CONFIG_DIR}/SRO.backup
                    rm -f ${CONFIG_DIR}/SRO.dtcl
                fi
                ;;
            2) 
                read -e -p "Should full server replication be removed? [y/N] " REMOVE_RSP
                REMOVE_RSP=$(echo $REMOVE_RSP | tr '[:upper:]' '[:lower:]')
                if [ -n "$REMOVE_RSP" -a "$REMOVE_RSP" = "y" ]; then
                    echo $"Removing full server replication configuration"
                    ${DTREPSETGENERATOR} -r
                    echo
                    echo $"A system reboot may be necessary to stop full server protection"
                    read -e -p "Press Enter to continue" ENTER
                fi
                ;;
            3)
                add_remove_volume
                ;;
            4)
                if [ -n "$(/etc/init.d/${DTBRAND_SERVICE_ALIAS} status | grep -w "running" 2>/dev/null || true)" ]; then
                    if verify_service_access "$(hostname)"; then
                        ${DTREPSETGENERATOR} -R 
                    else
                        echo $"$SERVICE_DISPLAY_NAME access could not be established, unable to display full server replication set."
                    fi
                else
                    echo $"$SERVICE_DISPLAY_NAME is not running, unable to display full server replication set."
                fi
                read -e -p "Press Enter to continue" ENTER
                ;;
            q)
                break;
                ;;
            --)
                break
                ;;
            *)
                echo "$SCRIPT_NAME:" $"usage error:" $"unrecognized option" "\"$MENU_OPTION\""
                ;;
        esac
    done
}

start_stop_dblt () {
    while :; do
        clear
        echo $"=== Service Start/Stop ==="
        echo
        echo $"=== Current $SERVICE_DISPLAY_NAME state ==="
        STATUS=$(/etc/init.d/$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
           MNT_VOLUMES=$(echo "${MOUNTED_VOLUMES//"\040"/ }") #SCR00233118 Changed by @IndusaDevTeam
           MNT_VOLUMES=$(echo "${MNT_VOLUMES//"\134"/\\}") #SCR00233118 Changed by @IndusaDevTeam
           echo "$MNT_VOLUMES"
        fi
        echo
        echo $"File Systems & Block Devices replicatable when $SERVICE_DISPLAY_NAME starts: "
        if [ -f "$DTFS_MOUNTS" ]; then
            while read MOUNTS JUNK; #SCR00233118 Added by @IndusaDevTeam
            do
               echo $MOUNTS
            done <"$DTFS_MOUNTS"
            AUTO_MOUNTS="DONE"
        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_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)
                /etc/init.d/$SERVICE_ALIAS start
                ;;
            2)
                /etc/init.d/$SERVICE_ALIAS stop
                ;;
            3)
                /etc/init.d/$SERVICE_ALIAS restart
                ;;
            4)
                /etc/init.d/$SERVICE_ALIAS reload
                ;;
            5)
                /etc/init.d/$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 HTML with $HTML_VIEWER"
        echo $"3.   View Users Guide HTML with $HTML_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 $"4.   View End User License Agreement TXT with $TXT_VIEWER"
        echo $"5.   View dtfs/dtrep module license TXT with $TXT_VIEWER"
        echo $"6.   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"/readme/"$DTBRAND_READMEHTML"
                    ;;
                2)
                    $HTML_VIEWER "$DTDOC_DIR"/Scripting\ Guide/"$DTBRAND_SCRIPTING_GUIDE"
                    ;;
                3)
                    $HTML_VIEWER "$DTDOC_DIR"/User\'s\ Guide/"$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"
                #    ;;
                4)
                    $TXT_VIEWER "$DTDOC_DIR"/license.txt
                    ;;
                5)
                    $TXT_VIEWER "$DTDOC_DIR"/Double-Take_kernel_module_GPLv2.txt
                    ;;
                6)
                    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 $1
    read -e -p $"Press Enter to continue. " ENTER
}

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
            ;;
        ioControlMaxDelay)
            test -n "$IO_CONTROL_MAXDELAY" && 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
            ;;
        ioControlMaxDelay)
            IO_CONTROL_MAXDELAY=500
            ;;
        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
            ;;
        ioControlMaxDelay)
            if ! [ "$VALUE" -eq "$VALUE" ] 2>/dev/null; then
                return 1
            elif [ "$VALUE" -lt 10 ]; then
                return 1
            elif [ "$VALUE" -gt $IO_CONTROL_DELAY_MAX ]; then
                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"}
                ;;
            ioControlMaxDelay)
                : ${IO_CONTROL_MAXDELAY:="$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=
            ;;
        ioControlMaxDelay)
            IO_CONTROL_MAXDELAY="$VALUE"
            MSG=$"Maximum Throttling Delay set to %d milliseconds.\n"
            ;;
        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)
                ;;
            ioControlMaxDelay)
                ;;
            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_MAXDELAY=
    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 \
        ioControlMaxDelay \
        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 Adaptive Throttling:       false Force Adaptive Throttling Active:  false
# Maximum Throttling Delay (msecs): yyzzz Throttling Delay Interval (msecs): yyzzz
# Throttling Start Level (percentage): nn Throttling Stop Level (percentage): nnnn
# Memory Usage Limit (bytes): wwxxxyyyzzz Max Write Buffer Size (bytes): xxxyyyzzz
# ---------------------------------------*---------------------------------------*
        # Translators will need to ensure that this stuff fits into 2 colums of
        # 40 characters each.
        printf $"Enable Adaptive Throttling: %11s " \
            $(bool_to_str "$IO_CONTROL_ENABLE")
        printf $"Force Adaptive Throttling Active: %6s\n" \
            $(bool_to_str "$IO_CONTROL_FORCE")
        printf $"Maximum Throttling Delay (msecs): %5d " "$IO_CONTROL_MAXDELAY"
        printf $"Throttling Delay Interval (msecs): %5d\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 $"Memory Usage Limit (bytes): %11d " "$MEMORY_LIMIT"
        printf $"Max Write Buffer Size (bytes): %9d\n" "$WRITE_CHUNK_SIZE"
        echo
        echo $"==========================================="
        echo $"Menu Options"
        echo $"1.    Toggle Adaptive Throttling (*)"
        echo $"2.    Toggle Forced Adaptive Throttling (*)"
        echo $"3.    Set Maximum Throttling Delay (in milliseconds)"
        echo $"4.    Set Throttling Delay Interval (in milliseconds)"
        echo $"5.    Set Throttling Start Level (percentage)"
        echo $"6.    Set Throttling Stop Level (percentage)"
        echo $"7.    Set Memory Usage Limit (bytes)"
        echo $"8.    Set Maximum Write Buffer Size (bytes)"
        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"
#                ;;
            1)
                toggle_boolean ioControlEnable
                rewrite_settings ioControlEnable "$IO_CONTROL_ENABLE"
                ;;
            2)
                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"
                ;;
            3)
                clear
                echo $"Set the Maximum Throttling Delay"
                echo "================================================================================"
                echo
                echo $"Press Enter to keep the current Maximum Throttling Delay."
                get_current_setting ioControlMaxDelay
                read -e -p $"Please enter the Maximum Throttling Delay (in milliseconds) ["$IO_CONTROL_MAXDELAY"]: " ENTRY
                if [ -z "$ENTRY" ]; then
                    ENTRY="$IO_CONTROL_MAXDELAY"
                fi

                if validate_setting ioControlMaxDelay "$ENTRY"; then
                    adjust_setting ioControlMaxDelay "$ENTRY"
                    rewrite_settings ioControlMaxDelay "$ENTRY"
                else
                    echo $"The Maximum Throttling Delay must be a positive integer between 10 and $IO_CONTROL_DELAY_MAX."
                fi
                ;;
            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 Menu"
        echo $"2.    Add/Remove users to $SERVICE_DISPLAY_NAME groups"
        echo $"3.    Configure File System or Block Device Replication"
        echo $"4.    Edit $SERVICE_DISPLAY_NAME config file (optional)"
        echo $"5.    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)
                activation_code_menu
                ;;
            2)
                add_remove_user
                ;;
            3)
                configure_automount
                ;;
            4)
                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
                ;;
            5)
                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 basic diagnostic info"
        echo $"3.    Collect and package detailed diagnostic info"
        echo $"4.    Collect and package full diagnostic info"
        echo $"5.    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 -cls
                ;;
            3)
                collect_dtinfo -clsd
                ;;
            4)
                collect_dtinfo -f
                ;;
            5)
                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)
                rm -rf ~/.DT
                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.
    -n CODES   Run non-interactively; interpret CODES as the add-on-codes
               and rewrite the configuration file accordingly.

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:n:" OPTION; do 
        case "$OPTION" in
            c)
                CONF_FILE="$OPTARG"
                ;;
            k)
                ACTIVATION_KEY="$OPTARG"
                INTERACTIVE=
                ;;
            n)
                ADDON_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
                ;;
            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 basic DT runlevels are setup
RC5_STARTUP=$(find /etc -name "S*${SERVICE_ALIAS}" | grep "rc5.d")
RC3_STARTUP=$(find /etc -name "S*${SERVICE_ALIAS}" | grep "rc3.d")
RC6_SHUTDOWN=$(find /etc -name "K*${SERVICE_ALIAS}" | grep "rc6.d")
if [ -z "$RC5_STARTUP" -o \
     -z "$RC3_STARTUP" -o \
     -z "$RC6_SHUTDOWN" ]; then
   /sbin/chkconfig --add ${SERVICE_ALIAS}
fi

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

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

if [ -n "$ADDON_KEY" ]; then
    # scriptable
    insert_addoncodes
fi

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

exit 0

