#!/usr/bin/env bash

# Wrapper script to gather all necessary smb data from the "isi smb" CLI

# This script is Zone aware, and loops through share configuration in
# a per zone manner

# This script replaces the previous commands called in 7.0
#
#   local_exe:
#       'isi_smb'
#

# Dump information:
#
#   Global config
#   Open sessions
#   Open files
#   For each zone:
#       Default share config for the zone
#       For each share in the zone:
#           Share info
#

CMD_BASE="/usr/bin/isi"
CMD_TIMEOUT="15"

if [ "$LINES" == "" ]; then
    H_BREAK=`tput -T xterm lines`
else
    H_BREAK=$LINES
fi

if [ "$H_BREAK" == "" ]; then
    H_BREAK=40
fi

execute_gather_command()
{
    local COMMAND="$CMD_BASE --timeout=$CMD_TIMEOUT smb $CMD_ARGS"

    for (( i=0; i<$H_BREAK; i++ )); do printf "-"; done; printf "\n"
    if [ "$CMD_ARGS" == "" ]; then
        echo " $HEADER"
    else
        echo " $HEADER: '$COMMAND'"
    fi
    for (( i=0; i<$H_BREAK; i++ )); do printf "-"; done; printf "\n"

    $COMMAND
}

#
# Global Config
#
HEADER="Global Settings"
CMD_ARGS="settings global view"
execute_gather_command

#
# Sessions
#
HEADER="Open Sessions"
CMD_ARGS="sessions list"
execute_gather_command

#
# Files
#
HEADER="Open Files"
CMD_ARGS="openfiles list"
execute_gather_command

#
# For each ZONE
#
ZONES=`isi zone zones list --no-header --no-footer | awk '{ print $1 }'`

for z in $ZONES; do

    HEADER="Zone '$z'"
    CMD_ARGS="settings shares view --zone=$z"
    execute_gather_command

    #
    # For each SHARE
    #
    SHARES=`isi smb shares list --no-header --no-footer --zone=$z | awk '{ print $1 }'`

    for s in $SHARES; do
        HEADER="($z) Share '$s'"
        CMD_ARGS="share view $s --zone=$z"
        execute_gather_command
    done

done

