# ============================== DATAD / DATADD ==============================
# [DATAD] Quick source shortcuts for NetScaler data scripts | Usage: datad / datadd / ddd | Example: datad
alias ddd="source /home/CITRITE/manjeshn/manscript/datad.sh"
alias datad="source /home/CITRITE/manjeshn/manscript/datad.sh"
alias datadd="source /home/CITRITE/manjeshn/manscript/datadd.sh"


# ============================== CONFETCH TOOLING =============================
# [CONFETCH] Wrapper + viewers for config fetch tooling | Usage: conFetch / show / showd | Example: conFetch <args>
alias show="python /home/CITRITE/manjeshn/manscript/show.py"
alias showd="python /home/CITRITE/manjeshn/manscript/showd.py"
alias conFetch="python /home/CITRITE/manjeshn/manscript/conFetch_Wrapper.py"


# ============================== BIGCAP ==============================
# [BIGCAP] Run bigcap helper script (packet/capture helper) | Usage: bigcap <args> | Example: bigcap -h
alias bigcap="python /home/CITRITE/manjeshn/manscript/bigcap.py"


# ============================== DISPOSABLE TOYS (dT) ==============================
# [DT] Run disposableToys dt utility | Usage: dt <args> | Example: dt --help
alias dt="python /home/CITRITE/manjeshn/manscript/disposableToys/Project_dT/dt.py"


# ============================== PARV TSHOOT STYLE ==============================
# [LS OVERRIDE] List files in long + reverse + all + human readable | Usage: ls <path> | Example: ls /var/log
alias ls="ls -lrha"


# ============================== ALLNEWNSLOG ==============================
# [ALLNEWNSLOG] Iterate collector*/var/nslog/newnslog* and run nsconmsg | Usage: allnewnslog <duration> | Example: allnewnslog 300
alias allnewnslog='function _allnewnslog() { base_dir="$(pwd | sed '\''s|\(.*collector[^/]*\)/.*|\1|'\'')"; find "$base_dir/var/nslog/" -maxdepth 1 -type d -name "newnslog*" -print0 | while IFS= read -r -d "" i; do echo -e "\033[1;33m------------------------ $i ------------------------\033[0m"; nsconmsg -K "$i" -d "$1" -s disptime=1; done; }; _allnewnslog'


# ============================== DIRECTORY SHORTCUTS ==============================
# [CD SHORTCUTS] Faster directory traversal | Usage: .. / ... / .2 etc | Example: ...  (go up 2 levels)
alias ..="cd .."
alias ...="cd ../../"
alias ....="cd ../../../"
alias .....="cd ../../.././"
alias .1="cd .."
alias .2="cd ../../"
alias .3="cd ../../../"
alias .4="cd ../../../../"


# ============================== HISTORY / CLEAR ==============================
# [HISTORY] Quick shell history shortcuts | Usage: h / gh <pattern> | Example: gh nslog
alias h='history'
alias gh="history | grep "
alias c="clear"


# ============================== COLORIZED GREP / LESS ==============================
# [GREP COLOR] Case-insensitive grep with persistent color | Usage: zzgrep <pattern> <file> | Example: zzgrep error ns.log
alias zzgrep='grep -i --color=always'

# [LESS COLOR] View ANSI-colored output safely in less | Usage: <cmd> | zzless | Example: cat out.txt | zzless
alias zzless='less -R'


# ============================== CSV COLUMN COUNTER ==============================
# [COUNTCOL] Print column index and first row values from CSV | Usage: countcol < file.csv | Example: head -1 a.csv | countcol
alias countcol="awk -F, '{for(i=1;i<=NF;i++) { print i, \$i } exit}'"


# ============================== FASTFIND FUNCTION ==============================
# [FASTFIND] Case-insensitive filename search under current dir | Usage: fastfind <token> | Example: fastfind nslog
fastfind () {
    find . -iname "*$1*" 2>/dev/null
}

# [LASTOOL] LAS Your Netscaler VPX
alias lastool="python /home/CITRITE/pashwani/NSTools/las_tool.py"

# =============== APPENDED SECTION: PCAP SSLKEYS INJECTOR ===============
# [PCAP TLS INJECTOR] Inject TLS secrets into captures using editcap | Usage: pcap-inject <ssl_keys> <pcap> [out.pcapng] | Example: pcap-inject sslkeys.log in.pcap out.pcapng

# [PCAP-SSL] Convenience alias for editcap TLS secret injection mode | Usage: pcap-ssl ... | Example: pcap-ssl "tls,sslkeys.log" in.pcap out.pcapng
alias pcap-ssl='editcap --inject-secrets tls'

# [PCAP-INJECT] Safe wrapper: validates inputs + prevents overwrite + creates .pcapng | Usage: pcap-inject <ssl_keys_file> <input_pcap> [output_pcapng] | Example: pcap-inject keys.log trace.pcap
pcap-inject() {
    if [ $# -ne 2 ] && [ $# -ne 3 ]; then
        echo "Usage: pcap-inject <ssl_keys_file> <input_pcap> [output_pcapng]"
        echo "If output_pcapng is omitted, uses input name with .pcapng extension"
        return 1
    fi

    local ssl_keys="$1"
    local input_pcap="$2"
    local output_pcapng="${3:-}"

    # [VALIDATION] Ensure SSL keys + PCAP exist before running editcap | Usage: automatic | Example: missing file => error
    if [ ! -f "$ssl_keys" ]; then
        echo -e "\033[31m? ERROR: SSL keys file not found: $ssl_keys\033[0m"
        return 1
    fi

    if [ ! -f "$input_pcap" ]; then
        echo -e "\033[31m? ERROR: Input PCAP not found: $input_pcap\033[0m"
        return 1
    fi

    # [OUTPUT NAME] Default output is input basename + .pcapng | Usage: omit 3rd arg | Example: foo.pcap => foo.pcapng
    if [ -z "$output_pcapng" ]; then
        if [[ "$input_pcap" == *.* ]]; then
            output_pcapng="${input_pcap%.*}.pcapng"
        else
            output_pcapng="${input_pcap}.pcapng"
        fi
    fi

    # [OVERWRITE GUARD] Prompt if output exists to avoid clobbering | Usage: automatic | Example: choose 'n' to abort
    if [ -f "$output_pcapng" ]; then
        read -rp "$(echo -e "\033[33m??  Output file '$output_pcapng' exists. Overwrite? (y/n) \033[0m")" confirm
        if [[ ! "$confirm" =~ [yY] ]]; then
            echo -e "\033[33mAborted by user\033[0m"
            return 1
        fi
    fi

    # [EXECUTION] Inject secrets and write output (pcap/pcapng supported) | Usage: automatic | Example: editcap --inject-secrets "tls,keys.log" in.pcap out.pcapng
    editcap --inject-secrets "tls,$ssl_keys" "$input_pcap" "$output_pcapng"
    
    # [RESULT] Print success/failure + basic output metadata | Usage: automatic | Example: shows size on success
    if [ $? -eq 0 ]; then
        echo -e "\n\033[32m? SUCCESS: Created $output_pcapng\033[0m"
        echo "   Input PCAP:  $input_pcap"
        echo "   SSL Keys:    $ssl_keys"
        echo "   Output Size: $(du -h "$output_pcapng" 2>/dev/null | awk '{print $1}')"
    else
        echo -e "\n\033[31m? FAILED: editcap returned error status\033[0m"
        echo "   Command: editcap --inject-secrets tls,$ssl_keys $input_pcap $output_pcapng"
        return 1
    fi
}

# ============================== PCAP-INJECT AUTO-COMPLETION ==============================
# [AUTOCOMPLETE] Tab-complete keys/pcap/output args for pcap-inject | Usage: type 'pcap-inject <TAB>' | Example: pcap-inject ssl<TAB>
_pcap-inject-completion() {
    local cur prev
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    case $COMP_CWORD in
        1)  # [COMPLETE ARG1] SSL keys file completion | Matches: *.sslkeys/*.keys/*.log | Example: keys<TAB>
            COMPREPLY=( $(compgen -f -X '!*@(sslkeys|keys|log)' -- "$cur") )
            ;;
        2)  # [COMPLETE ARG2] Input capture completion | Matches: *.pcap/*.cap/*.pcapng/*.trace | Example: in.p<TAB>
            COMPREPLY=( $(compgen -f -X '!*@(pcap|cap|pcapng|trace)' -- "$cur") )
            ;;
        3)  # [COMPLETE ARG3] Output file completion | Any filename | Example: out.pcapng<TAB>
            COMPREPLY=( $(compgen -f -- "$cur") )
            ;;
    esac
}

# [SHELL OPT] Enable extended glob needed for the completion filters | Usage: automatic | Example: older shells ignore safely
shopt -s extglob 2>/dev/null

# [REGISTER] Bind completion function to pcap-inject | Usage: automatic | Example: completion works in bash
complete -F _pcap-inject-completion pcap-inject 2>/dev/null

# [LOAD BANNER] Friendly message showing injector loaded | Usage: automatic on shell load | Example: appears on new terminal
echo -e "\033[36m>>  PCAP TLS Injector loaded. Use 'pcap-inject' <<\033[0m"

# ============================== AUTO-UPDATE BASH_PROFILE ==============================
# [AUTO-UPDATE] Pull the latest .bash_profile from git | Usage: automatic on shell load
_auto_update_profile() {
    # [LOCAL TESTING GUARD] Bypass update if DISABLE_PROFILE_UPDATE=1
    if [ "$DISABLE_PROFILE_UPDATE" = "1" ]; then
        echo -e "\033[1;33m>>  Auto-update skipped (DISABLE_PROFILE_UPDATE=1) <<\033[0m"
        return 0
    fi

    local remote_url="https://git.4parv.in/parv.ashwani/.bash_profile/raw/main/.bash_profile"
    local local_file="$HOME/.bash_profile"
    local tmp_file="/tmp/.bash_profile_new"

    # [GUARD] Prevent infinite loops if the new profile sources itself
    if [ "$_PROFILE_UPDATE_RUN" = "1" ]; then
        return 0
    fi
    export _PROFILE_UPDATE_RUN="1"

    # [FETCH] Download quietly with a 2-second timeout to avoid shell hangs
    if curl -sL --connect-timeout 2 -m 2 "$remote_url" -o "$tmp_file" 2>/dev/null; then
        
        # [CHECK] If file has content and differs from the local version
        if [ -s "$tmp_file" ] && ! cmp -s "$local_file" "$tmp_file" 2>/dev/null; then
            echo -e "\033[1;35m>>  New .bash_profile detected on Git! Updating... <<\033[0m"
            
            # Backup current profile and overwrite with new
            cp "$local_file" "${local_file}.bak" 2>/dev/null
            cp "$tmp_file" "$local_file"
            
            # Clean up temp file before sourcing to keep environment clean
            rm -f "$tmp_file" 2>/dev/null
            
            # Apply the newly downloaded profile immediately
            source "$local_file"
            return 0
        fi
    fi
    
    # Clean up if no update was needed or curl failed
    rm -f "$tmp_file" 2>/dev/null
}

# Run the update check
_auto_update_profile