#!/usr/bin/env bash
#
# Use this script to build, configure, activate and deactivate Tranalyzer plugins.
# Run t2conf --help for a full list of options.

source "$(dirname "$0")/../t2utils.sh"

# Default values
EDITOR="${EDITOR:-$(which vim)}"
T2CONFRC="$SHOME/t2confrc"
PLUGIN_FOLDER="$HOME/.tranalyzer/plugins"
DISABLED_FOLDER="$PLUGIN_FOLDER/disabled"
PLUGIN_LIST="$PLUGIN_FOLDER/plugins.load"
PLUGIN_STATE="/tmp/t2pl_state"

usage() {
    printf "Usage:\n"
    printf "    $SNAME [OPTION...] [PLUGIN...]\n\n"
    printf "Action arguments:\n"
    printf "    -I               list the configuration flags available for the plugin\n"
    printf "    -G name          get the value of the define 'name'\n"
    printf "    -D name=default  reset the define 'name' to its default value\n"
    printf "    -D name=value    set the define 'name' to 'value'\n"
    printf "                     (options only available if ONE plugin is being configured)\n"
    printf "\n"
    printf "    -g default       shorter way to point to a plugin 'default.config' file\n"
    printf "    -g [file]        generate config 'file' for the current configuration\n"
    printf "                     (if 'file' is omitted, create 'pluginName.config')\n"
    printf "    -C file          load and apply configuration 'file' whose format is\n"
    printf "                     FLAG = VAL\n"
    printf "                     (if 'file' is 'auto', use 'pluginName.config',\n"
    printf "                     if 'file' is 'default', use 'default.config')\n"
    printf "    --reset          load 'default.config' to reset the default configuration\n"
    printf "\n"
    printf "    --patch file     configure tranalyzer according to 'file' whose format is\n"
    printf "                     FLAG <tab> NEWVAL <tab> OLDVAL <tab> FILE or\n"
    printf "                     FLAG <tab> VAL <tab> FILE\n"
    printf "                     where FILE is relative '-t' option\n"
    printf "    --rpatch file    same as --patch, but restore OLDVAL\n"
    printf "\n"
    printf "Tranalyzer2 configuration arguments:\n"
    printf "    --t2             configure/build Tranalyzer2 first\n"
    printf "    --dual           activate IPv4 and IPv6 dissection\n"
    printf "    --ip6            activate IPv6 dissection (deactivate IPv4)\n"
    printf "    --ip4            activate IPv4 dissection (deactivate IPv6)\n"
    printf "    --eth            activate Ethernet flows\n"
    printf "    --noeth          deactivate Ethernet flows\n"
    printf "    -m               activate monitoring mode\n"
    printf "\n"
    printf "Plugins configuration arguments:\n"
    printf "    -c               run \$EDITOR for every requested plugin\n"
    printf "\n"
    printf "    -a               activate all plugins\n"
    printf "    -0               deactivate all plugins\n"
    printf "\n"
    printf "    -9               activate pcapd only\n"
    printf "    -q               deactivate pcapd and restore previous state\n"
    printf "\n"
    printf "    -L [file]        edit plugins loading list 'file'\n"
    printf "                     [default: ~/.tranalyzer/plugins/plugins.load]\n"
    printf "    -S [file]        show active plugins in loading list 'file'\n"
    printf "                     [default: ~/.tranalyzer/plugins/plugins.load]\n"
    printf "\n"
    printf "    -s [file]        save list of loaded plugins in 'file' [/tmp/t2pl_state]\n"
    printf "    -r [file]        restore previous list of plugins from 'file' [/tmp/t2pl_state]\n"
    printf "\n"
    printf "Build arguments:\n"
    printf "    -l               lazy mode (only build plugins if they do not exist)\n"
    printf "    -f               force rebuild of the plugins (./autogen.sh -r)\n"
    printf "    -d               build plugins in debug mode (./autogen.sh -d)\n"
    printf "\n"
    printf "GUI arguments:\n"
    printf "    --gui            run the graphical (command-line) configurator\n"
    printf "    -n               sort by plugin name instead of plugin number\n"
    printf "\n"
    printf "Optional arguments:\n"
    printf "    -t path          set tranalyzer folder to 'path' [$T2HOME]\n"
    printf "    -p path          set plugin folder to 'path' [~/.tranalyzer/plugins]\n"
    printf "    -x               exit after performing --t2, -a, -r, -p, -q, --patch or\n"
    printf "                     --rpatch option\n"
    printf "    -y               do not ask for confirmation before executing an action\n"
    printf "    -v               enable verbose mode\n"
    printf "\n"
    printf "Help and documentation arguments:\n"
    printf "    -h               display this help and exit\n"
}

# $1: plugin name or tranalyzer2 or utils
get_abs_path() {
    if [ -z "$1" ]; then
        printerr "missing argument for function get_abs_path"
        exit 1
    fi

    local _name="$1"
    if [ "$_name" = "tranalyzer2" ] || [ "$_name" = "utils" ]; then
        echo "$T2HOME/$_name"
    else
        echo "$T2PLHOME/$_name"
    fi
}

# $1: plugin name or tranalyzer2 or utils
goto_folder() {
    if [ -z "$1" ]; then
        printerr "missing argument for function goto_folder"
        exit 1
    fi

    cd "$(get_abs_path "$1")"
}

# $1: plugin name
conf_plugin() {
    if [ -z "$1" ]; then
        printerr "missing argument for function conf_plugin"
        exit 1
    fi

    local _name="$(tr -d "/" <<< "$1")"
    goto_folder "$_name"

    if [ -n "$RESET" ]; then
        CONFIG="default.config"
        if [ ! -f "$CONFIG" ]; then
            [ $VERBOSE ] && printwrn "No default configuration file available for '$_name'"
            return
        fi
        validate_config_file "default.config"
    fi

    if [ -n "$CONFIG" ]; then
        local _file
        for _file in ${CONFIG[@]}; do
            if [ -f "$_file" ] && [ -n "$(grep -E "^#\\s+:name:\\s+$_name\\s*#?$" "$_file")" ]; then
                if [ -f "t2plconf" ] && [ "$GUI" ]; then
                    ./t2plconf -g "$_file"
                else
                    t2_config_apply "$_name" "$_file"
                fi
            fi
        done
    elif [ -f "t2plconf" ] && [ $GUI ]; then
        ./t2plconf
    elif [ -f "src/$_name.hpp" ]; then
        $EDITOR "src/${_name}.hpp"
    elif [ -f "src/$_name.h" ]; then
        $EDITOR "src/${_name}.h"
    else
        printerr "No configuration method available for '$_name'"
        printinf "Try using '$SNAME -D' option"
    fi
}

build_t2() {
    cd "$T2HOME/tranalyzer2/"

    if [ $LAZY ] && [ -x "$(get_t2_exec)" ]; then
        true
    else
        "$T2BUILD" tranalyzer2 $FORCE $DEBUG
    fi

    T2STAT=$?
    if [ $T2STAT -ne 0 ]; then
        if [ ! $GUI ]; then
            exit 1
        fi

        echo "Press [Enter] to return to the menu, 'C' to continue and 'X' to exit"
        local _act
        read _act
        _act="$(tr '[:lower:]' '[:upper:]' <<< "$_act")"
        if [ "X" = "$_act" ]; then
            exit 1
        fi
    fi
}

# $1: plugin index
build_plugin() {
    if [ -z "$1" ]; then
        printerr "missing argument for function build_plugin"
        exit 1
    fi

    local _index="$1"
    local _name="${PLUGINS[$_index]}"
    local _plugin_so="$(find_most_recent_file "$PWD" "lib${_name}.so")"

    if [ $LAZY ] && [ -n "$(ls "$DISABLED_FOLDER" | grep "_${_name}.so$")" ]; then
        mv "$DISABLED_FOLDER/"*"_${_name}.so" "$PLUGIN_FOLDER"
        BUILT[${#BUILT[@]}]="$_name"
    elif [ $LAZY ] && [ -f "$_plugin_so" ]; then
        cp "$_plugin_so" "$PLUGIN_FOLDER/${_index}_${_name}.so"
        BUILT[${#BUILT[@]}]="$_name"
    else
        cd "$T2PLHOME/$_name"

        if [ $CONF ]; then
            if [ -f "src/${_name}.hpp" ]; then
                $EDITOR "src/${_name}.hpp"
            else
                $EDITOR "src/${_name}.h"
            fi
        fi

        if ! "$T2BUILD" "$_name" $FORCE $DEBUG -p "$PLUGIN_FOLDER"; then
            FAILED[${#FAILED[@]}]="$_name"
        else
            BUILT[${#BUILT[@]}]="$_name"
        fi

        cd ..
    fi
}

save_state() {
    if [ "$(ls "$PLUGIN_FOLDER" | grep .so$)" ]; then
        ls "$PLUGIN_FOLDER" | grep .so$ > "$PLUGIN_STATE"
    fi
}

restore_state() {
    if [ -f "$PLUGIN_STATE" ] && [ -n "$(file -i "$PLUGIN_STATE" | grep "text/plain")" ]; then
        deactivate_all
        local _i
        for _i in $(cat "$PLUGIN_STATE"); do
            local _num="$(cut -d_ -f1 <<< "$_i")"
            if [[ "${_num:0:1}" != "#" ]]; then
                build_plugin "$_num"
            fi
        done
    else
        printerr "file '$PLUGIN_STATE' does not exist or has invalid format"
        exit 1
    fi
}

deactivate_all() {
    if [ -n "$(ls "$PLUGIN_FOLDER" | grep .so$)" ]; then
        if [ $LAZY ]; then
            mv "$PLUGIN_FOLDER/"*so "$DISABLED_FOLDER"
        else
            rm -f "$PLUGIN_FOLDER/"*so
        fi
    fi
}

activate_pcapd() {
    if [ ! -d "$T2PLHOME/pcapd" ]; then
        printerr "pcapd plugin not available"
        exit 1
    fi

    save_state
    deactivate_all
    build_plugin "$(grep "PLUGINORDER=" "$T2PLHOME/pcapd/autogen.sh" | cut -d= -f2)"
}

deactivate_pcapd() {
    restore_state
    if [ "$(ls "$PLUGIN_FOLDER" | grep _pcapd.so$)" ]; then
        if [ $LAZY ]; then
            mv "$PLUGIN_FOLDER"/*_pcapd.so "$DISABLED_FOLDER"
        else
            rm -f "$PLUGIN_FOLDER"/*_pcapd.so
        fi
    fi
}

show_plugin_list() {
    if [ ! -f "$PLUGIN_LIST" ]; then
        printerr "'$PLUGIN_LIST' does not exist"
        exit 1
    fi

    AWK '/^\s*$/ { next } !/^#/ { print }' "$PLUGIN_LIST"
}

edit_plugin_list() {
    local old_plugin_list

    if [ -f "$PLUGIN_LIST" ]; then
        old_plugin_list="$(mktemp)"
        mv "$PLUGIN_LIST" "$old_plugin_list"
    fi

    touch "$PLUGIN_LIST"

    if [ ! $ALL ] && [ ! $NONE ] && [ -z "$plugins" ] && [ -z "$PCAPD" ]; then
            plugins=(
                basicFlow
                basicStats
                connStat
                icmpDecode
                macRecorder
                protoStats
                tcpFlags
                tcpStates
                txtSink
            )
    fi

    local _sorted=$(tr ' ' '\n' <<< "${PLUGINS[*]}" | sort)

    local _plugin
    for _plugin in ${_sorted[@]}; do
        if [ $ALL ] || [ -n "$(grep -Fw "$_plugin" <<< "${plugins[@]}")" ] || [ -n "$PCAPD" -a "$_plugin" = "pcapd" ]; then
            echo "$_plugin" >> "$PLUGIN_LIST"
        elif [ -n "$PCAPD" ] && [ -n "$(grep -w "^$_plugin" "$old_plugin_list")" ]; then
            echo "##$_plugin" >> "$PLUGIN_LIST"
        elif [ -n "$DPCAPD" ] && [ -n "$(grep -Fw "##$_plugin" "$old_plugin_list")" ]; then
            echo "$_plugin" >> "$PLUGIN_LIST"
        else
            echo "#$_plugin" >> "$PLUGIN_LIST"
        fi
    done
    [ $VERBOSE ] && printok "Successfully created '$PLUGIN_LIST'"
}

predef_settings() {
    cd "$T2HOME"

    local _c=0
    local _desc=()
    local _act=()
    local _line

    while read _line; do
        if [ -z "$_line" ] || [ -n "$(grep "^##[[:space:]]*" <<< "$_line")" ]; then
            continue # skip empty lines and comments
        elif [ -n "$(grep "^#[[:space:]]*" <<< "$_line")" ]; then
            _desc+=($_c)
            _desc+=("$(perl -pe 's/^#\s*//' <<< "$_line" | perl -pe 's/\s*\[on\]|\[off\]\s*$//')")
            # TODO set to current value?
            _desc+=("$(perl -lpe 's/^#\s*.*\s*\[(on|off)\]\s*$/\1/' <<< "$_line")")
            _c=$((_c+1))
        else
            _act[$((_c-1))]+="$_line | "
        fi
    done < "$T2CONFRC"

    dialog --no-lines --no-shadow --title "Tranalyzer2" \
            --ok-label "Build" --extra-button --extra-label "Back" \
            --checklist "Select options: " 20 70 20 \
            "${_desc[@]}" 2> "$TEMPFILE"

    local _ret=$?
    if [ $_ret -eq 0 ] || [ $_ret -eq 1 ]; then # build or back
        local _i
        for _i in $(seq 0 $((_c-1))); do
            local _on="$(grep "\b$_i\b" "$TEMPFILE")"
            while IFS="|" read _line; do
                _line="$(perl -pe 's/^\s*//' <<< "$_line")"
                _line="$(perl -pe 's/\s*$//' <<< "$_line")"
                [ -z "$_line" ] && continue

                local _d _v1 _v2 _f
                while IFS=$'\t' read -r _d _v1 _v2 _f; do
                    if [ ! -f "$_f" ]; then
                        printerr "t2confrc: '$_f' is not a valid file"
                    elif [ -z "$_d" ] || [ -z "$_v1" ] || [ -z "$_v2" ]; then
                        printerr "t2confrc: invalid line: '$_line'"
                    elif [ -n "$_on" ]; then
                        [ $VERBOSE ] && printf "set_define_in_file %s %s %s\n" "$_d" "$_v1" "$_f"
                        set_define_in_file "$_d" "$_v1" "$_f"
                    else
                        [ $VERBOSE ] && printf "set_define_in_file %s %s %s\n" "$_d" "$_v2" "$_f"
                        set_define_in_file "$_d" "$_v2" "$_f"
                    fi
                done <<< "$_line"
            done <<< "$(tr '|' '\n' <<< "${_act[$_i]}")"
        done
    fi

    rm -f "$TEMPFILE"

    return $_ret
}

# $1: plugin name
# $2: define name
# $3: [optional]
#       - file or folder where to search for header files
#       - 'default' to get the default value for the define
get_define() {
    if [ -z "$1" ] || [ -z "$2" ]; then
        printerr "missing argument for function get_define"
        exit 1
    fi

    local _plugin="$1"
    local _name="$2"
    local _file="$3"

    local _generate="$GENERATE"

    local _files
    if [ "$_file" = "default" ]; then
        if [ "$_plugin" = "tranalyzer2" ] || [ "$_plugin" = "utils" ]; then
            _file="$T2HOME"
        else
            _file="$T2PLHOME"
        fi
        _file="$_file/$_plugin/default.config"
        _files=("$_file")
        _generate=1
    elif [ $GENERATE ]; then
        _file="$CONFIG"
        _files=("$_file")
    elif [ -f "$_file" ]; then
        _files=("$_file")
    elif [ -d "$_file" ]; then
        [ -n "$(ls "$_file/"*.hpp 2> /dev/null)" ] && _files+=("$_file"/*.hpp)
        [ -n "$(ls "$_file/"*.h   2> /dev/null)" ] && _files+=("$_file"/*.h)
    elif [ -n "$_file" ]; then
        printerr "file '$_file' does not exist"
        exit 1
    else
        local _utilsdir
        local _srcdir="$(get_abs_path "$_plugin")"
        if [ "$_plugin" != "utils" ]; then
            _utilsdir="$(get_abs_path "utils")"
            _srcdir="$_srcdir/src"
        fi

        [ -n "$(ls "$_srcdir/"*.hpp 2> /dev/null)" ] && _files+=("$_srcdir"/*.hpp)
        [ -n "$(ls "$_srcdir/"*.h   2> /dev/null)" ]   && _files+=("$_srcdir"/*.h)

        if [ -d "$_utilsdir" ]; then
            _files+=("$_utilsdir"/*.h)
        fi

        if [ "$_plugin" = "tranalyzer2" ]; then
            _files+=("$_srcdir/proto/"*.h)
        fi
    fi

    if [ $_generate ]; then
        if [ -z "$(grep "^$_name\s*=\s*" "$_file")" ]; then
            local _utils="$T2HOME/utils"
            if [ "$(basename "$_file")" != "default.config" ] && [ -f "$T2HOME/utils/utils.config" ]; then
                _utils="$_utils/utils.config"
            else
                _utils="$_utils/default.config"
            fi
            if [ -z "$(grep "^$_name\s*=\s*" "$_utils")" ]; then
                printerr "Configuration flag '$_name' does not exist in '$_file'"
                exit 1
            fi
            _file="$_utils"
        fi
        AWK "/^$_name\s*=\s*/ { print; exit }" "$_file"
    else
        if [ -z "$(grep "^#define\s\+$_name\s\+" "${_files[@]}")" ]; then
            # Macro does not exist in src... maybe it exists in utils?
            _files=("$T2HOME/utils/"*.h)
            if [ -z "$(grep "^#define\s\+$_name\s\+" "${_files[@]}")" ]; then
                printerr "macro '$_name' does not exist in '$_file'"
                exit 1
            fi
        fi

        # Only return the first occurence (the 'exit' is there to handle cases where a define is redefined, e.g., CS_GEOLOC in connStat)
        perl -nle "if (/^#define\s+$_name\s+([^\s]((?!\s*\/[\/\*]|\s*$).)*).*$/) { print \"$_name = \$1\"; exit }" "${_files[@]}"
    fi
}

# simple wrapper to call set_define without a plugin name
# $1: define name
# $2: define new value
# $3: file or folder where to search for header files
set_define_in_file() {
    set_define "" "$1" "$2" "$3"
}

# $1: plugin name
# $2: define name
# $3: define new value
# $4: file or folder where to search for header files [optional]
set_define() {
    if [ -z "$2" ] || [ -z "$3" ]; then
        printerr "missing argument for function set_define"
        exit 1
    fi

    local _plugin="$1"
    local _name="$2"
    local _value="$3"
    local _file="$4"

    if [ "$_value" = "default" ]; then
        _value="$(get_define "$_plugin" "$_name" "default")"
        _value="$($SED 's/^[^=]\+= //' <<< "$_value")"
    fi

    local _files
    if [ $GENERATE ]; then
        _file="$CONFIG"
        _files=("$_file")
    elif [ -f "$_file" ]; then
        _files=("$_file")
    elif [ -d "$_file" ]; then
        [ -n "$(ls "$_file/"*.hpp 2> /dev/null)" ] && _files+=("$_file"/*.hpp)
        [ -n "$(ls "$_file/"*.h   2> /dev/null)" ] && _files+=("$_file"/*.h)
    elif [ -n "$_file" ]; then
        printerr "file '$_file' does not exist"
        exit 1
    elif [ -z "$_plugin" ]; then
        printerr "set_define: a plugin name (\$1) or a file/folder (\$4) MUST be provided"
        exit 1
    else
        local _utilsdir
        local _srcdir="$(get_abs_path "$_plugin")"
        if [ "$_plugin" != "utils" ]; then
            _utilsdir="$(get_abs_path "utils")"
            _srcdir="$_srcdir/src"
        fi

        [ -n "$(ls "$_srcdir/"*.hpp 2> /dev/null)" ] && _files+=("$_srcdir"/*.hpp)
        [ -n "$(ls "$_srcdir/"*.h   2> /dev/null)" ] && _files+=("$_srcdir"/*.h)

        if [ -d "$_utilsdir" ]; then
            _files+=("$_utilsdir"/*.h)
        fi

        if [ "$_plugin" = "tranalyzer2" ]; then
            _files+=("$_srcdir/proto/"*.h)
        fi
    fi

    # escape /, *, & and . from $_value
    local _newval="$($SED 's/\([/*&.]\)/\\\1/g' <<< "$_value")"
    if [ "$_newval" = '"\t"' ]; then
        _newval='"\\t"'
    fi

    if [ $GENERATE ]; then
        if [ -z "$(grep "^$_name\s*=\s*" "$_file")" ]; then
            local _utils="$T2HOME/utils"
            if [ "$(basename "$_file")" != "default.config" ] && [ -f "$T2HOME/utils/utils.config" ]; then
                _utils="$_utils/utils.config"
            else
                _utils="$_utils/default.config"
            fi
            if [ -z "$(grep "^$_name\s*=\s*" "$_utils")" ]; then
                printerr "Configuration flag '$_name' does not exist in '$_file'"
                exit 1
            fi
            _file="$_utils"
        fi
        perl -i -pe "!\$found && s/^$_name\s*=\s*[^#\n]+/$_name = $_newval/p && (\$found = 1)" "$_file"
    else
        if [ -z "$(grep "^#define\s\+$_name\s\+" "${_files[@]}")" ]; then
            if [ -n "$_plugin" ]; then
                printerr "macro '$_name' does not exist for '$_plugin'"
            else
                printerr "macro '$_name' does not exist in '$_file'"
            fi
            return 1
        fi

        # Only replace the first occurence (the 'found' is there to handle cases where a define is redefined, e.g., CS_GEOLOC in connStat)
        perl -i -pe "!\$found && s/(^#define\s+$_name\s+)([^\s]((?!\s*\/[\/\*]|\s*$).)*)(.*$)/\${1}$_newval\${4}/p && (\$found = 1)" "${_files[@]}"
    fi
}

# $1: config file to validate
validate_config_file() {
    local _file="$1"
    if [ ! -f "$_file" ]; then
        printerr "file '$_file' does not exist"
        exit 1
    fi

    local _err="$(AWK -F'\\s*=\\s*' '
        /^#\s+:name:\s+/ {
            name = gensub(/^#\s+:name:\s+([^[:space:]]+)\s+#$/, "\\1", "g")
        }
        /^#/ || /^%/ || /^[[:space:]]*$/ { next } # skip comments and empty lines
        NF != 2 {
            print "Invalid line in config file: expected two columns, separated by \"=\", found " NF ":\n" $0
            exit
        }
        END {
            if (!name) {
                print "Invalid config file: no section starting with \"# :name: \""
            }
        }
    ' "$_file")"

    if [ -n "$_err" ]; then
        printerr "$_err"
        exit 1
    fi
}

# $1: plugin name
# $2: configuration file to apply
t2_config_apply() {
    local _name="$1"
    local _file="$2"

    if [ ! -f "$_file" ]; then
        printerr "$_name: file '$_file' does not exist"
        exit 1
    fi

    goto_folder "$_name"
    [ $VERBOSE ] && printinf "'$_name': Loading configuration file '$_file'"

    # save IFS
    local _oldifs="$IFS"

    local _n _v _f
    while IFS=$'\t' read -r _n _v _f; do
        [ -z "$_n" -o -z "$_v" -o -z "$_f" ] && continue
        case "$_v" in
            [yY][eE][sS]) _v=1;;
                [nN][oO]) _v=0;;
        esac
        if [ ! -f "$_f" ] && [ -f "${_f}pp" ]; then
            # C++ header file
            _f="${_f}pp"
        fi
        set_define "$_name" "$_n" "$_v" "$_f"
    done <<< "$(AWK -F'\\s*=\\s*' -v OFS="\t" '
        /^#\s+:name:\s+/ {
            name = gensub(/^#\s+:name:\s+([^[:space:]]+)\s+#$/, "\\1", "g")
            file = "src/" name ".h"
        }
        /^#\s+:file:\s+/ {
            file = gensub(/^#\s+:file:\s+([^[:space:]]+)\s+#$/, "\\1", "g")
        }
        /^#/ || /^%/ || /^[[:space:]]*$/ { next } # skip comments and empty lines
        file { print $1, $2, file }
    ' "$_file")"

    # restore IFS
    IFS="$_oldifs"
}

# $1: plugin name
# $2: configuration file to generate
t2_config_generate() {
    local _name="$1"
    local _dest="$2"
    local _oldpwd="$PWD"

    [ $VERBOSE ] && printinf "Generating configuration file '$_dest'"
    goto_folder "$_name"

    local _default="default.config"
    if [ ! -f "$_default" ]; then
        printerr "Cannot generate a config file for '$_name': no '$_default' file available"
        return 1
    fi

    AWK -F'\\s*=\\s*' -v OFS="\t" -v plugin="$_name" -v dest="$(basename "$_dest")" '
        BEGIN {
            print "# This is the configuration file for " plugin
            print "#"
            print "# Apply the configuration as follows:"
            print "#     - t2conf " plugin " -C " dest
            print "#"
        }
        /^# \[Format of the file\]$/ {
            format = 1
            print
            next
        }
        format { print; next }
    ' "$_default" > "$_dest"

    cd "$_oldpwd"
    [ $VERBOSE ] && printok "Successfully generated configuration file '$_dest'"
    return 0
}

# $1: plugin name
# $2: configuration file to update
t2_config_update() {
    local _name="$1"
    local _file="$2"

    if [ ! -f "$_file" ]; then
        printerr "$_name: file '$_file' does not exist"
        exit 1
    fi

    [ $VERBOSE ] && printinf "Updating configuration file '$_file'"

    _file="$($READLINK -f "$_file")"

    # save PWD
    local _oldpwd="$PWD"

    goto_folder "$plugin"

    # save IFS
    local _oldifs="$IFS"

    local _n _v _f
    while IFS=$'\t' read -r _n _v _f; do
        [ -z "$_n" -o -z "$_v" -o -z "$_f" ] && continue
        if [ ! -f "$_f" ] && [ -f "${_f}pp" ]; then
            # C++ header file
            _f="${_f}pp"
        fi
        local _newval="$(AWK "/^#define\s+$_n\s+/ { print; exit }" "$_f")"
        _newval="$(perl -pe "s/(^#define\s+$_n\s+)([^\s]((?!\s*\/[\/\*]|\s*$).)*)(.*$)/\$2/p" <<< "$_newval")"
        if [ "$_newval" = '"\t"' ]; then
            _newval='"\\t"'
        fi
        local _oldval="$(AWK -F= "/^$_n\s*=\s*/ { print \$2; exit }" "$_file" | $SED 's/^\s*//')"
        case "$_oldval" in
            "yes"|"no")
                if [ "$_newval" = "0" ]; then
                    _newval="no"
                elif [ "$_newval" = "1" ]; then
                    _newval="yes"
                fi
                ;;
        esac
        $SED -i "s|^\($_n\s*=\s*\)\(.*\)$|\1$_newval|" "$_file"
    done <<< "$(AWK -F'\\s*=\\s*' -v OFS="\t" '
        /^#\s+:name:\s+/ {
            name = gensub(/^#\s+:name:\s+([^[:space:]]+)\s+#$/, "\\1", "g")
            file = "src/" name ".h"
        }
        /^#\s+:file:\s+/ {
            file = gensub(/^#\s+:file:\s+([^[:space:]]+)\s+#$/, "\\1", "g")
        }
        /^#/ || /^%/ || /^[[:space:]]*$/ { next } # skip comments and empty lines
        file { print $1, $2, file }
    ' "$_file")"

    cd "$_oldpwd"

    # restore IFS
    IFS="$_oldifs"
}

validate_patch() {
    cd "$T2HOME"
    [ $VERBOSE ] && printf "Validating patch '%s'\n" "$PATCH"

    local _err="$(AWK -F"\t" -v rpatch="$RPATCH" '
        /^#/ || /^%/ || /^[[:space:]]*$/ { next } # skip comments and empty lines
        old_nf == 0 { old_nf = NF }
        old_nf != NF {
            print "Invalid patch: " old_nf " columns expected, found " NF ":\n" $0
            exit
        }
        NF == 3 && rpatch {
            print "Cannot revert patch: four columns required, only three found:\n" $0
            exit
        }
        NF != 3 && NF != 4 {
            print "Invalid patch: expected three or four columns, found " NF ":\n" $0
            exit
        }
        {
            old_nf = NF
        }
    ' "$PATCH")"

    if [ -n "$_err" ]; then
        printerr "$_err"
        exit 1
    fi
}

# $1: plugin name
t2_list_define() {
    if [ -z "$1" ]; then
        printerr "missing argument for function t2_list_define"
        exit 1
    fi

    local _plugin="$1"
    goto_folder "$_plugin"

    if [ -f default.config ]; then
        AWK -F= '
            /^#\s*:from:\s*/ { p = 1; next }
            p {
                if (match($0, /^#\s*-\s*([A-Z0-9_]+)\s*#$/, _flag)) {
                    print _flag[1]
                } else {
                    p = 0
                }
                next
            }
            /^#/ || NF < 2 { next }
            {
                print $1
            }' default.config
    elif [ -f t2plconf ]; then
        AWK -v name="$_plugin" '
            /^ITEMS=/ {
                start = 1
                next
            }
            /^\)\s*$/ {
                start = 0
                exit
            }
            start && /^\s*[A-Z_]+\s*/ {
                found = 1
                print $1
            }
            END {
                if (!found) {
                    print "No configuration flags found for " name
                }
            }' t2plconf
    elif [ -f "tests/$_plugin.flags" ]; then
        AWK -v name="$_plugin" '
            !/^#/ && NF == 2 {
                found = 1
                print $1
            }
            END {
                if (!found) {
                    print "No configuration flags found for " name
                }
            }' "tests/$_plugin.flags"
    else
        printerr "No configuration method available for '$_plugin'"
    fi
}

# $1: plugin name
t2_get_define() {
    if [ -z "$1" ]; then
        printerr "missing argument for function t2_get_define"
        exit 1
    fi

    local _plugin="$1"

    local _name
    for _name in ${GET_DEFINE[@]}; do
        get_define "$_plugin" "$_name"
    done
}

# $1: plugin name
t2_set_define() {
    if [ -z "$1" ]; then
        printerr "missing argument for function t2_set_define"
        exit 1
    fi

    local _plugin="$1"

    # save and change IFS
    local _oldifs="$IFS"
    IFS=$'\n'

    local _i
    for _i in ${DEFINE[@]}; do
        local _name="$($SED 's/^\([^=]\+\)=.*$/\1/' <<< "$_i")"
        local _old="$(get_define "$_plugin" "$_name")"
        _old="$($SED 's/^[^=]\+= //' <<< "$_old")"
        local _value="$($SED 's/^[^=]\+=\(.*\)$/\1/' <<< "$_i")"
        if [ "$_value" != "default" ]; then
            # Make sure the new value matches the type of the old value
            if [ "$(AWK '/^"/ && /"$/' <<< "$_old")" ] && [ ! "$(AWK '/^"/ && /"$/' <<< "$_value")" ]; then
                #printwrn "$_name represents a string, but '$_value' appears not to be properly quoted."
                #ask_default_no "Proceed with the replacement anyway" || continue
                if [ "$_value" != "NULL" ]; then
                    if [ ! "$(AWK '/^"/' <<< "$_value")" ]; then
                        _value="\"$_value"
                    fi
                    if [ ! "$(AWK '/"$/' <<< "$_value")" ]; then
                        _value="$_value\""
                    fi
                fi
            elif [ "$(AWK "/^'/ && /'$/" <<< "$_old")" ] && [ ! "$(AWK "/^'/ && /'$/" <<< "$_value")" ]; then
                #printwrn "$_name represents a character, but '$_value' appears not to be properly quoted."
                #ask_default_no "Proceed with the replacement anyway" || continue
                if [ ! "$(AWK "/^'/" <<< "$_value")" ]; then
                    _value="'$_value"
                fi
                if [ ! "$(AWK "/'$/" <<< "$_value")" ]; then
                    _value="$_value'"
                fi
            elif [ "$_old" = "yes" ] || [ "$_old" = "no" ]; then
                if [ "$_value" != "yes" ] && [ "$_value" != "no" ] && [ "$_value" != 0 ] && [ "$_value" != 1 ]; then
                    printwrn "$_name represents a boolean, but '$_value' appears not to be a boolean (0, 1, yes, no)."
                    ask_default_no "Proceed with the replacement anyway" || continue
                fi
            elif [ -z "$(tr -d '[0-9]' <<< "$_old")" ] && [ -n "$(tr -d '[0-9]' <<< "$_value")" ]; then
                if [ "$_value" = 'yes' ]; then
                    _value=1
                elif [ "$_value" = 'no' ]; then
                    _value=0
                else
                    printwrn "$_name represents a number, but '$_value' appears not to be a number."
                    ask_default_no "Proceed with the replacement anyway" || continue
                fi
            fi
        fi

        set_define "$_plugin" "$_name" "$_value"
    done

    # restore IFS
    IFS="$_oldifs"
}

t2_patch() {
    cd "$T2HOME"

    validate_patch

    [ $VERBOSE ] && printf "Applying patch '%s'\n" "$PATCH"

    # save IFS
    local _oldifs="$IFS"

    local _n _v _f
    while IFS=$'\t' read -r _n _v _f; do
        [ -z "$_n" -o -z "$_v" -o -z "$_f" ] && continue
        [ $VERBOSE ] && printf "set_define_in_file %s %s %s\n" "$_n" "$_v" "$_f"
        set_define_in_file "$_n" "$_v" "$_f"
    done <<< "$(AWK -F"\t" -v OFS="\t" -v val=$((RPATCH+2)) '
        /^#/ || /^%/ || /^[[:space:]]*$/ { next } # skip comments and empty lines
        NF == 3 { print $1, $2, $3 }
        NF == 4 { print $1, $val, $4 }
    ' "$PATCH")"

    # restore IFS
    IFS="$_oldifs"

    [ $VERBOSE ] && printf "Finished applying patch '%s'\n" "$PATCH"
}

print_t2_stat() {
    if [ $BUILDT2 ] && [ $T2STAT ] && [ $T2STAT -ne 2 ]; then
        if [ $T2STAT -ne 0 ]; then
            printerr "\nFailed to build Tranalyzer2\n"
        else
            printok "\nTranalyzer2 successfully built\n"
        fi
    fi
}

print_pl_stat() {
    local _i
    local _sorted

    if [ $VERBOSE ] && [ ${#BUILT[@]} -ne 0 ]; then
        printok "\nThe following plugins were successfully built:"
        _sorted=$(tr ' ' '\n' <<< "${BUILT[*]}" | sort)
        for _i in $_sorted; do
            printok "    $_i"
        done
    fi

    if [ ${#FAILED[@]} -ne 0 ]; then
        printerr "\nThe following plugins could not be built:"
        _sorted=$(tr ' ' '\n' <<< "${FAILED[*]}" | sort)
        for _i in $_sorted; do
            printerr "    $_i"
        done
        exit 1
    fi

    if [ -z "$(ls "$PLUGIN_FOLDER" | grep ".so$")" ]; then
        printwrn "\nNo plugin activated\n"
    fi
}

_cleanup() {
    local _ret=$1
    [ -f "$TEMPFILE" ] && rm -f "$TEMPFILE"
    exit $_ret
}

if [ $# -eq 0 ]; then
    usage
    exit 1
fi

plugins=()
while [ $# -gt 0 ]; do
    case $1 in
        -p)
            validate_next_arg "$1" "$2"
            if [ -e "$2" ] && [ ! -d "$2" ]; then
                printerr "Option '$1': '$2' is not a directory"
                abort_with_help
            fi
            [ ! -d "$2" ] && mkdir "$2"
            PLUGIN_FOLDER="$($READLINK -f "$2")"
            DISABLED_FOLDER="$PLUGIN_FOLDER/disabled"
            [ -z "$EDITPLLIST" ] && PLUGIN_LIST="$PLUGIN_FOLDER/plugins.load"
            shift
            ;;
        -t)
            validate_next_arg "$1" "$2"
            if [ ! -d "$2" ]; then
                printerr "Option '$1': '$2' is not a directory"
                abort_with_help
            fi
            T2HOME="$($READLINK -f "$2")"
            T2PLHOME="$T2HOME/plugins"
            shift
            ;;
        -s)
            SAVE=1
            if [ -n "$2" ]; then
                PLUGIN_STATE="$($READLINK -f "$2")"
                shift
            fi
            ;;
        -r)
            RESTORE=1
            if [ -n "$2" ]; then
                if [ ! -f "$2" ]; then
                    printerr "Option '$1': '$2' is not a valid file"
                    abort_with_help
                fi
                PLUGIN_STATE="$($READLINK -f "$2")"
                shift
            fi
            ;;
        -L|-S)
            if [ "$1" = "-S" ]; then
                SHOWPLLIST=1
            else
                EDITPLLIST=1
            fi
            if [ -n "$2" ] && [ "${2:0:1}" != "-" ] &&
               [ ! -f "$T2PLHOME/$2/autogen.sh" ] &&
               [ "$2" != "tranalyzer2" ] && [ "$2" != "utils" ];
            then
                PLUGIN_LIST="$2"
                shift
            fi
            ;;
        --reset)
            RESET=1
            ;;
        -g|--generate)
            if [ "$2" ] && ! arg_is_option "$2" &&
               [ ! -f "$T2PLHOME/$2/autogen.sh" ] &&
               [ "$2" != "tranalyzer2" ] && [ "$2" != "utils" ]
            then
                if [ "$2" = "default" ]; then
                    CONFIG+=("$2")
                else
                    CONFIG+=("$($READLINK -f "$2")")
                fi
                shift
            fi
            GENERATE=1
            ;;
        -C|--config)
            if [ ! -f "$2" ] && [ "$2" = "auto" -o "$2" = "default" ]; then
                CONFIG="$2"
            else
                validate_next_file "$1" "$2"
                validate_config_file "$2"
                CONFIG+=("$($READLINK -f "$2")")
            fi
            shift
            ;;
        --rpatch|--patch)
            validate_next_arg "$1" "$2"
            if [ ! -f "$2" ]; then
                printerr "Option '$1': '$2' is not a valid file"
                abort_with_help
            fi
            PATCH="$($READLINK -f "$2")"
            if [ "${1:2:1}" == "r" ]; then
                RPATCH=1
            fi
            shift
            ;;
        -I)
            LIST_DEFINE=1
            ;;
        -G)
            validate_next_arg "$1" "$2"
            GET_DEFINE+=("$2")
            shift
            ;;
        -D)
            validate_next_arg "$1" "$2"
            if [ -z "$(AWK -F= 'NF == 2' <<< "$2")" ]; then
                printerr "Option '$1': expected name=value, found '$2'"
                abort_with_help
            fi
            DEFINE+=("$2")
            shift
            ;;
        # T2 core configuration
        --t2) BUILDT2=1;;
        --dual) DUAL=1; BUILDT2=1;;
        --ip6) IP6=1; BUILDT2=1;;
        --ip4) IP4=1; BUILDT2=1;;
        --eth) ETH=1; BUILDT2=1;;
        --noeth) NOETH=1; BUILDT2=1;;
        --[gt]ui) GUI=1;;
        -m|--monitoring) MON=1; BUILDT2=1;;
        -a|--all) ALL=1;;
        -0|--none) NONE=1;;
        -9|--pcapd) PCAPD=1;;
        -q) DPCAPD=1;;
        -x) EXIT=1;;
        -c) CONF=1;;
        -d|--debug) DEBUG="-d";;
        -f|--force) FORCE="-r";;
        -l|--lazy) LAZY=1;;
        -n) GUI=1; SORTNAME=1;;
        -y|--yes) YES=1;;
        -v|--verbose) VERBOSE=1;;
        -h|--help) usage; exit 0;;
        *)
            if [ ! -f "$T2PLHOME/$1/autogen.sh" ] &&
               [ "$1" != "tranalyzer2" ] && [ "$1" != "utils" ]
            then
                abort_option_unknown "$1"
            fi
            plugins+=($1)
            ;;
    esac
    shift
done

if [ $ALL ] && [ $NONE ]; then
    printerr "Cannot activate all and no plugins at the same time"
    exit 1
fi

if [ ! $GUI ]; then
    OPTS=(
        $BUILDT2 $SAVE $RESTORE $PATCH
        $RESET $GENERATE ${CONFIG[@]}
        $LIST_DEFINE ${GET_DEFINE[@]} ${DEFINE[@]}
        $DUAL $IP4 $IP6 $ETH $NOETH $MON
        $NONE $ALL $PCAPD $DPCAPD $CONF
        $EDITPLLIST $SHOWPLLIST
    )
    if [ ${#plugins[@]} -eq 0 ] && [ ${#OPTS[@]} -eq 0 ]; then
        printerr "One of --gui, -s/-r, --reset -g, -C --patch/--rpatch, -I, -G, -D, -L, --dual/--ip4/--ip6/--eth/--noeth/-m, -a/-0/-9/-q/-c option and/or a plugin name is required"
        abort_with_help
    fi
fi

if [ ! -d "$T2HOME" ]; then
    printerr "Tranalyzer folder '$T2HOME' does not exist"
    printf "Use '-t' option to specify the correct path\n"
    exit 1
fi

if [ ! -x "$(get_t2_exec)" ] && [ -z "$EDITPLLIST$SHOWPLLIST" ]; then
    BUILDT2=1
fi

# associative arrays were introduced in bash 4
if [[ ${BASH_VERSINFO[0]} < 4 ]]; then
    printerr "minimum bash version required is '4', found '$(cut -d- -f1 <<< "$BASH_VERSION")'"
    exit 1
fi

if [ $GUI ]; then
    # Dependencies
    check_dependency dialog

    DVER="$(dialog --version | AWK '{print $2}')"
    if [[ $(cut -d- -f1 <<< "$DVER") < 1.1 ]] ||
       [[ $(cut -d- -f2 <<< "$DVER") < 20120703 ]]; then
        printerr "minimum dialog version required is '1.1-20120703', found '$DVER'"
        exit 1
    fi

    # Dialog return value
    OK=0
    CANCEL=1
    HELP=2
    EXTRA=3
    ITEM_HELP=4
    ESC=255

    # setup TEMPFILE
    TEMPFILE=`(tempfile) 2> /dev/null` || TEMPFILE=/tmp/test$$
fi

trap "trap - SIGTERM && _cleanup 1" HUP INT QUIT TERM
trap "_cleanup \$?" EXIT

# t2conf plugin -I
if [ -n "$LIST_DEFINE" ]; then
    if [ ${#plugins[@]} -ne 1 ]; then
        printerr "-I option can only be used with ONE plugin"
        abort_with_help
    fi
    t2_list_define "${plugins[0]}"
    exit 0
fi

# t2conf plugin -G define
if [ -n "$GET_DEFINE" ]; then
    if [ ${#plugins[@]} -ne 1 ]; then
        printerr "-G option can only be used with ONE plugin"
        abort_with_help
    fi
    plugin="${plugins[0]}"
    if [ "$GENERATE" ]; then
        pluginHome="$(get_abs_path "$plugin")"
        if [ -z "$CONFIG" ]; then
            CONFIG="$pluginHome/$plugin.config"
        elif [ "$CONFIG" = "default" ]; then
            CONFIG="$pluginHome/default.config"
        fi
        if [ ! -f "$CONFIG" ]; then
            printerr "Configuration file '$CONFIG' does not exist"
            exit 1
        fi
    fi
    t2_get_define "$plugin"
    exit 0
fi

# t2conf plugin -D define
if [ -n "$DEFINE" ]; then
    if [ ${#plugins[@]} -ne 1 ]; then
        printerr "-D option can only be used with ONE plugin"
        abort_with_help
    fi
    plugin="${plugins[0]}"
    if [ "$GENERATE" ]; then
        pluginHome="$(get_abs_path "$plugin")"
        [ -z "$CONFIG" ] && CONFIG="$pluginHome/$plugin.config"
        if [ "$CONFIG" = "default" ] || [ "$($READLINK -f "$CONFIG")" = "$pluginHome/default.config" ]; then
            printerr "Cannot edit default configuration files"
            exit 1
        fi
        if [ ! -f "$CONFIG" ]; then
            t2_config_generate "$plugin" "$CONFIG" || exit 1
        fi
    fi
    t2_set_define "$plugin"
    exit 0
fi

if [ -n "$CONFIG$RESET$GENERATE" ]; then

    if [ ${#plugins[@]} -eq 0 ]; then
        plugins=(tranalyzer2 utils)
        if [ $ALL ]; then
            IGNORE=(t2PSkel)
            for plugin in $T2PLHOME/*; do
                P="${plugin##**/}"
                BLACKLISTED=$(grep -w "$P" <<< "${IGNORE[*]}")
                if [ -f "$plugin/autogen.sh" ] && [ ! "$BLACKLISTED" ]; then
                    plugins+=("$P")
                fi
            done
        else
            # No plugins specified, assume the default plugins
            plugins+=(
                basicFlow
                basicStats
                connStat
                icmpDecode
                macRecorder
                protoStats
                tcpFlags
                tcpStates
                txtSink
            )
        fi
    fi

    if [ -n "$RESET" ]; then
        for plugin in ${plugins[@]}; do
            conf_plugin "$plugin"
        done
        exit 0
    fi

    if [ -n "$GENERATE" ]; then

        if [ -n "$CONFIG" ] && [ ${#plugins[*]} -gt 1 ]; then
            printerr "Cannot specify a filename with '-g' option and multiple plugins"
            exit 1
        fi

        if [ -z "$CONFIG" ]; then
            for plugin in ${plugins[@]}; do
                pluginHome="$(get_abs_path "$plugin")"
                newConfig="$pluginHome/$plugin.config"
                defaultConfig="$pluginHome/default.config"
                if [ ! -f "$defaultConfig" ]; then
                    printerr "Cannot generate a config file for '$plugin': no 'default.config' file available"
                    continue
                fi
                CONFIG+=("$newConfig")
            done
        fi
    fi

    for plugin in ${plugins[@]}; do
        for file in ${CONFIG[@]}; do
            if [ ! -f "$file" ]; then
                pluginHome="$(get_abs_path "$plugin")"
                if [ "$file" = "auto" ]; then
                    file="$pluginHome/$plugin.config"
                elif [ "$file" = "default" ]; then
                    file="$pluginHome/default.config"
                fi
            fi

            if [ -f "$file" ]; then
                if [ -z "$(grep -E "^#\\s+:name:\\s+$plugin\\s*#?$" "$file")" ]; then
                    # Config file not for this plugin
                    continue
                fi

                if [ -n "$GENERATE" ] && [ ! "$GUI" ]; then
                    printwrn "$plugin: file '$file' already exists..."
                    printf "Overwrite it (y/N)? "
                    if [ -z "$YES" ]; then
                        read ans
                    else
                        ans="yes"
                        echo "$ans"
                    fi
                    case $ans in
                        [yY]|[yY][eE][sS]) ;;
                        *) continue;;
                    esac
                fi
            fi

            if [ -n "$GENERATE" ]; then
                if [ ! -f "$file" ] || [ ! "$GUI" ]; then
                    t2_config_generate "$plugin" "$file" || continue
                fi
            fi

            if [ -f "$file" ] && [ -n "$(grep -E "^#\\s+:name:\\s+$plugin\\s*#?$" "$file")" ] && [ ! "$GUI" ]; then
                if [ -n "$GENERATE" ]; then
                    t2_config_update "$plugin" "$file"
                else
                    t2_config_apply "$plugin" "$file"
                fi
                break
            fi
        done
    done

    if [ ! "$GUI" ]; then
        exit 0
    fi
fi

if [ -n "$PATCH" ]; then
    t2_patch
    exit 0
fi

if [ ! -d "$PLUGIN_FOLDER" ]; then
    printwrn "Plugin folder '$PLUGIN_FOLDER' does not exist..."
    printf "Create it (Y/n)? "

    if [ -z "$YES" ]; then
        read ans
    else
        ans="yes"
        echo "$ans"
    fi

    case $ans in
        [yY]|[yY][eE][sS]|"")
                if ! mkdir -p "$PLUGIN_FOLDER"; then
                    printerr "could not create folder '$PLUGIN_FOLDER'"
                    exit 1
                fi
                ;;
             *)
                printf "Use '-p' option to specify a different path\n"
                exit 1;;
    esac
fi

if [ ${#plugins[@]} -gt 0 ] && [ -z "$EDITPLLIST$SHOWPLLIST" ]; then
    for plugin in ${plugins[@]}; do
        conf_plugin "$plugin"
    done
    exit 0
fi

if [ $BUILDT2 ]; then
    cd "$T2HOME/tranalyzer2/src"

    if [ $DUAL ]; then
        set_define "tranalyzer2" "IPV6_ACTIVATE" "2"
        unset LAZY
    elif [ $IP6 ]; then
        set_define "tranalyzer2" "IPV6_ACTIVATE" "1"
        unset LAZY
    elif [ $IP4 ]; then
        set_define "tranalyzer2" "IPV6_ACTIVATE" "0"
        unset LAZY
    fi

    if [ $ETH ]; then
        set_define "tranalyzer2" "ETH_ACTIVATE" "1"
        unset LAZY
    elif [ $NOETH ]; then
        set_define "tranalyzer2" "ETH_ACTIVATE" "0"
        unset LAZY
    fi

    if [ $MON ]; then
        set_define "tranalyzer2" "MONINTPSYNC"    "1"
        set_define "tranalyzer2" "MONINTTMPCP"    "1"
        set_define "tranalyzer2" "VERBOSE"        "0"
        set_define "tranalyzer2" "DIFF_REPORT"    "1"
        set_define "tranalyzer2" "MACHINE_REPORT" "1"
        unset LAZY
    fi

    if [ $EXIT ]; then
        tput clear
        exit 0
    fi

    if [ ! $GUI ]; then
        build_t2
    else
        HDRF=(main.h networkHeaders.h packetCapture.h tranalyzer.h)
        if [ -f "$T2CONFRC" ]; then
            HDR+=(0 "Predefined settings")
        fi
        if [ -f "$T2HOME/tranalyzer2/t2plconf" ]; then
            HDR+=(1 "t2plconf")
        fi
        c=2
        for i in ${HDRF[@]}; do
            HDR+=($c "$i")
            c=$((c+1))
        done
        HDR+=($c "Select a file...")
        FACT=$c
        ret=3
        while [ $ret -eq 3 ] || [ "C" != "$act" ]; do
            act="C"
            exec 3>&1
            select=$(dialog --title "Tranalyzer2" --clear \
                --ok-label "Build T2" \
                --default-item "$select" \
                --extra-button --extra-label "Edit" \
                --menu "Select 'Predefined settings' or a header file:" 20 70 20 \
                "${HDR[@]}" 2>&1 1>&3)
            ret=$?
            exec 3>&-
            tput clear
            if [ $ret -eq 3 ]; then
                if [ $select -eq 0 ]; then
                    predef_settings
                elif [ $select -eq 1 ]; then
                    "../t2plconf"
                elif [ $select -eq $FACT ]; then
                    FILE="$(dialog --stdout --title "Tranalyzer2" --clear --fselect "$T2HOME/tranalyzer2/src/" 20 70)"
                    if [ -n "$FILE" ] && [ -f "$FILE" ]; then
                        $EDITOR "$FILE" # edit selected file
                    fi
                else
                    $EDITOR "${HDRF[$((select-1))]}" # edit selected file
                fi
            fi
            if [ $ret -eq 0 ]; then
                build_t2
            elif [ $ret -ne 3 ]; then
                T2STAT=2
            fi
        done
    fi

    if [ $EXIT ] && [ ! $ALL ] && [ ! $PCAPD ] && [ ! $DPCAPD ] && [ ! $RESTORE ]; then
        tput clear
        print_t2_stat
        exit 0
    fi
fi

if [ $LAZY ] && [ ! -d "$DISABLED_FOLDER" ]; then
    mkdir -p "$DISABLED_FOLDER"
fi

declare -A PLUGINS

IGNORE=(t2PSkel)

for plugin in "$T2PLHOME/"*; do
    P="${plugin##**/}"
    BLACKLISTED=$(grep -w "$P" <<< "${IGNORE[*]}")
    if [ -d "$plugin" ] && [ -f "$plugin/autogen.sh" ] && [ ! "$BLACKLISTED" ]; then
        N="$(grep "^PLUGINORDER=" $plugin/autogen.sh | cut -d= -f2)"
        if [ "${#N}" -eq 3 ] && [ -n "$P" ]; then
            if [ -n "${PLUGINS[$N]}" ]; then
                printerr "Error: a plugin with number $N already exists: ${PLUGINS[$N]}, $P"
                unset -v PLUGINS
                exit 1
            fi
            PLUGINS["$N"]="$P"
        fi
    fi
done

if [ ! $GUI ] && [ $EDITPLLIST ]; then
    edit_plugin_list
    exit 0
elif [ ! $GUI ] && [ $SHOWPLLIST ]; then
    show_plugin_list
    exit 0
fi

if [ $RESTORE ]; then
    restore_state
fi

if [ $PCAPD ]; then
    activate_pcapd
elif [ $DPCAPD ]; then
    deactivate_pcapd
fi

if [ $EXIT ]; then
    if [ $ALL ]; then
        deactivate_all
        for i in ${!PLUGINS[@]}; do
            build_plugin "$i"
        done
    fi
    tput clear
    print_t2_stat
    print_pl_stat
    if [ $SAVE ]; then
        save_state
    fi
    exit 0
fi

if [ $GUI ]; then
    if [ $SORTNAME ]; then
        SORT="sort -k2"
    else
        SORT="sort -n"
    fi

    INDEX=0

    ret=$CANCEL
    while [ $ret -ne $OK ]; do
        ALL=$(for i in ${!PLUGINS[@]}; do
            if [ -s "$TEMPFILE" ]; then
                if [ -n "$(grep "\b$i\b" "$TEMPFILE")" ]; then
                    echo "$i ${PLUGINS[$i]} on"
                else
                    echo "$i ${PLUGINS[$i]} off"
                fi
            elif [ $EDITPLLIST ]; then
                if [ $ALL ]; then
                    echo "$i ${PLUGINS[$i]} on"
                elif [ $NONE ]; then
                    echo "$i ${PLUGINS[$i]} off"
                elif [ ! -f "$PLUGIN_LIST" ] || [ -n "$(AWK -v p="^[0-9]{3}_${PLUGINS[$i]}.so$" '$0 ~ p' "$PLUGIN_LIST")" ]; then
                    echo "$i ${PLUGINS[$i]} on"
                else
                    echo "$i ${PLUGINS[$i]} off"
                fi
            elif [ ! $ALL ] && {
                [ -z "$(ls "$PLUGIN_FOLDER" | grep ${i}_${PLUGINS[$i]}.so)" ] ||
                [ $NONE ]
            };
            then
                echo "$i ${PLUGINS[$i]} off"
            else
                echo "$i ${PLUGINS[$i]} on"
            fi
        done | $SORT)

        XTRA="--help-button --help-label Configure --help-status"
        if [ -z "$EDITPLLIST" ]; then
            OKLABEL="Build"
        else
            OKLABEL="OK"
        fi

        dialog --no-lines --no-shadow --title "Tranalyzer2" \
            --ok-label "$OKLABEL" --default-item "$INDEX" \
            $XTRA \
            --checklist "\nSelect plugins:\n\nUse the space bar to activate/deactivate plugins" 20 70 20 \
            $(xargs <<< "$ALL") 2> "$TEMPFILE"
        ret=$?

        case $ret in
            $OK) ;;
            $HELP) # Configure
                INDEX="$(AWK '{ print $2 }' "$TEMPFILE" | tr -d \")"
                conf_plugin "${PLUGINS[$INDEX]}"
                perl -i -pe 's/^HELP\s+\d{3}\s*//' "$TEMPFILE" # Removed HELP $INDEX
                ;;
            *)
                rm -f "$TEMPFILE"
                unset -v PLUGINS
                tput clear
                exit 0
                ;;
        esac
    done

    if [ "$TEMPFILE" ]; then
        if [ "$EDITPLLIST" ]; then
            rm -f "$PLUGIN_LIST"
            for i in ${!PLUGINS[@]}; do
                if [ -n "$(grep -w "$i" "$TEMPFILE")" ]; then
                    echo "${i}_${PLUGINS[$i]}.so" >> "$PLUGIN_LIST"
                else
                    echo "#${i}_${PLUGINS[$i]}.so" >> "$PLUGIN_LIST"
                fi
            done
            sort -o "$PLUGIN_LIST" "$PLUGIN_LIST"
        else
            deactivate_all
            for i in $(cat "$TEMPFILE"); do
                build_plugin "$i"
            done
        fi
        rm -f "$TEMPFILE"
    fi
fi

unset -v PLUGINS

tput clear
print_t2_stat
print_pl_stat

if [ $SAVE ]; then
    save_state
fi
