#!/bin/bash
#--------------------------------------------------------------------
# show_tech_cflow - Cflow show tech command
#
# Copyright (c) 2019 by cisco Systems, Inc.
# All rights reserved.
#--------------------------------------------------------------------

# Load the script provided by show-tech infra, which provides worker functions
#
source /opt/cisco/calvados/script/show_tech_main_fragment

__cardtype="unspecified"
__tar_file_directory_on_node="unspecified"
__file="unspecified"

arg_string=""
showtech_argv=""
showtech_argc="0"


while [ "$#" -gt "0" ]; do
    case "$1" in
        -t) __cardtype="$2"; shift 2;;
        *) showtech_argv="$showtech_argv $1"; (( showtech_argc+=1 )); shift 1;;
    esac
done

#
# Call the showtech infra default parser - using set to recreate the $#, $@,
# etc. - "--" is necessary so set doesn't try to interpret any of the
# arguments we are passing through!
#
if [[ $showtech_argc -ne 0 ]]; then
    set -- $showtech_argv
    default_parser_function $@
fi

if [ "$__cardtype" == "unspecified" ]; then
    __cardtype=`/opt/cisco/calvados/script/node_type`
fi

if [ "$__tar_file_directory_on_node" == "unspecified" ]; then
    echo "ABORT: showtech directory unspecified"
    exit
fi

if [ ! -d "$__tar_file_directory_on_node" ]; then
    echo "ABORT: showtech directory $__showtech_directory does not exist"
    exit
fi

if [ "$__file" == "unspecified" ]; then
    echo "ABORT: dsc node name not unspecified"
    exit
fi

collect_cflow_data() {

    print_main_heading "Collect cflow data"

    /bin/bash /opt/cisco/calvados/script/cflow_copy.sh

    local cflow_dir="/misc/disk1/cflow"
    if [ ! -d $cflow_dir ]; then
        cflow_dir="/misc/scratch/cflow"
    elif [ ! "$(ls -A $cflow_dir)" ]; then
        cflow_dir="/misc/scratch/cflow"
    fi

    local temp_dir="$cflow_dir"_temp
    local archive_dir="$temp_dir"/misc/scratch

    mkdir -p $archive_dir
    mv $cflow_dir $archive_dir
    tar --dereference -uf $__tar_file_directory_on_node/"$__file".cflow.tar -C $temp_dir .
    if [ -f $__tar_file_directory_on_node/"$__file".cflow.tar ];
    then
        gzip $__tar_file_directory_on_node/"$__file".cflow.tar
        rm -rf $temp_dir
    fi

}

# Script
display() {
    print_main_heading "show tech-support cflow"

    if [ "$__cardtype" != "SYS" ]; then
        collect_cflow_data
    fi
    print_main_heading "show tech-support complete"
}

# Run the appropriate function depending on the node specified and if a
# file is specified write the output to that file. We need to redirect
# stderr to stdout when writing to a file because some of the show
# commands output to stderr instead of stdout
source /opt/cisco/calvados/script/show_tech_file_fragment

