#!/bin/bash

file_path=$(pwd)/$(dirname "$0")

echo '#!/bin/bash

function _hint_file() {
    cur="${COMP_WORDS[COMP_CWORD]}"
    COMPREPLY=()
    if [ "$cur" == "~" ]; then
        cur="~/"
    fi
    opts=$(compgen -f -- "$cur")
    array=($opts)
    if [ ${#array[@]} -le 1 ]; then
        folder_path_expanded="${array/#\~/$HOME}" #use to replace ~ 
        if [ -d "$folder_path_expanded" ]; then
            opts=$(compgen -f -- "$array/")
            for opt in $opts; do
                COMPREPLY+=("$opt")
            done
        else
            COMPREPLY+=("$array")
        fi
    else
        for opt in $opts; do
            if [ -d "$opt" ]; then
                COMPREPLY+=("$opt/")
            else
                COMPREPLY+=("$opt")
            fi
        done
    fi
}

function _ecat_server() {
    local cur prev opts
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD - 1]}"
    if [[ ${COMP_CWORD} == 1 ]];then
        opts="server console log update analyse tests convert_csvfile autorun --help"
        COMPREPLY=()
        COMPREPLY=($(compgen -W "$opts" -- ${cur}))
    else
        _hint_file
    fi
    return 0
}

complete -F _ecat_server ecat_server

' > ${file_path}/.pcie_boot_env.sh

echo "ecat_server_path=${file_path}" >> ${file_path}/.pcie_boot_env.sh
echo "create ${file_path}/.pcie_boot_env.sh"

echo "
pathlist=\$(echo \$PATH | sed 's/:/\n/g' | sort | uniq)

ecat_server_path_is_exist=0
for dir in \$pathlist
do
    if test -d \$dir; then
        if [ "\$dir" == "\$ecat_server_path" ]; then
            ecat_server_path_is_exist=1
            break
        fi
    fi
done
if [ "\$ecat_server_path_is_exist" == "0" ]; then
    export PATH=\$PATH:\$ecat_server_path
fi
" >> ${file_path}/.pcie_boot_env.sh

echo "source ${file_path}/.pcie_boot_env.sh" >> ~/.bashrc
echo "add \"source ${file_path}/.pcie_boot_env.sh\" in ~/.bashrc"
source ${file_path}/.pcie_boot_env.sh

echo "ecat_server take effect."


