# shell

name: k
value:
#################################################################
# Copyright CEP (License : GPL)
# Kage New Shell Command/Library
#      /1994 make my commands to initial shell library(for BBS)
#      /2003 adding my cluster commands
#      /2008 upgrade to formula libraries
#      /2012 reduce and rewrite to compressed command
# 03/28/2014 initial version of Kage new command k for test 
# 03/31/2014 upgrade function for using old shell libraries and muerge old commands to KC
# 05/26/2014 upgrade array in shell to good works
# 05/29/2014 upgrade to fast working on library loading 
# 04/11/2016 upgrade AI type question and many upgrade
#$version$:0.4.35
#################################################################
# "${@}"    : put arrary
# ${#@}     : total array num
# ${@:#}    : all values after shift # to the array
# ${@:#:1}  : 1["]th values after shift # to the array
# ${@:#:f#} : 1 ~ f#["]s values after shift # to the array

KTAG=".k"
# _k_   : Kage function
# _kv_  : Kage variable

_k_exit() {
   local rc
   rc=$1
   [ -n "$rc" ] || rc=0
   if echo $0 | grep "^-" >/dev/null; then
       return $rc 
   else
       exit $rc
   fi
}

error_exit() {
   echo "$*"
   if echo $0 | grep "^-" >/dev/null; then
       return 1
   else
       exit 1
   fi
}

_k_dbg() {
    local dbg_level zz ii
    dbg_level=$1
    shift 1
    [ -n "$dbg_level" ] || dbg_level=1
    (( "$_kv_dbg" >= "$dbg_level" )) || return 0
    zz=0
    for ((ii=$((${#FUNCNAME[*]}-1));ii>=1; ii--)); do
       for ((uu=0; uu<=zz; uu ++)); do
           echo -n "  " 1>&2
       done
       [ "$ii" == "1" ] && echo -n "+ ${FUNCNAME[$ii]} : " 1>&2 || echo "+ ${FUNCNAME[$ii]}" 1>&2

       zz=$(($zz+1))
    done
    echo "$*" 1>&2
}

_k_log() {
    echo "$(date) : ${FUNCNAME[1]} : $*"
}

_k_k_help() {
    echo "
    k.k <cmd> <sub cmd> [<option>]
    or 
    k.k <cmd> [ <option> ]
    $(_k_version_info $0) 

    <cmd>  : library command or k command or linux command
    list   : showing loaded library cmd list when running cmd
    make_temp <cmd name> : make a temporary cmd file to _K_BIN directory
    setup  : setup default configuration to system

    <option>
    --help : each k command["]s help
    "
    _k_exit
}

# output local shell["]s functions list
_k_k_list() {
    declare -F | while read line; do
        ff=($line)
        echo "${ff[${#ff[*]}-1]} "
    done
}

_k_version() {
    if [ ! -n "$_K_VER" ]; then
       cd $(dirname "$(_k_readlink -f "$0")")
       export _K_VER=$(git describe --tags --long 2>/dev/null || echo "-")
    fi
    echo "Version: $_K_VER"
}

_k_version_info() {
  local file
  file=${@:1:1}
  if echo $0 |grep "^-" >& /dev/null; then
      echo "Version: Not a shell."
  else
      [ -f "$file" ] || error_exit "$(basename $0) <filename>"
#      echo "$file :"
      echo "Version: $(awk -F: ["]{if($1=="#$version$") print $2}["] $file)"
  fi
}

_k_file_version() {
    _k_version_info $@
}

# function finding sample
_k_bin() {
   local func cmd fcmd
   func=${@:1:1}
   cmd=${@:2:1}
   if [ ! -n "$func" -o ! -n "$cmd" ]; then
       echo "No input command"
       _k_exit 1
   fi

   if declare -F ${func}_$cmd >&/dev/null; then
      echo ${func}_$cmd
   elif declare -F _k_$cmd >&/dev/null; then
      echo _k_$cmd
   elif declare -F $cmd >&/dev/null; then
      echo $cmd
   else
      if echo $cmd | grep "^/" >& /dev/null; then
          [ -f $cmd ] && echo $cmd
      elif fcmd=$(_k_find_file $(basename "${cmd}${KTAG}") $_K_BIN $_K_LIB) ; then
          echo $fcmd
      elif fcmd=$(_k_find_file $cmd $PATH); then
          echo $fcmd
	  else
          echo "$cmd not found"
          _k_exit 1
      fi
   fi
   return 0
}

# load to shell
_k_load() {
    local name
    name=${@:1:1}
    [ -n "$name" ] || return 1
    [ -f $name ] && source $name
    unset name
}

# base starting sample
_k_k() {
   local cmd rcmd libs lname tfunc dbg shiftn
   shiftn=1
#set -x
#echo ">>${@}<<"
   if (( ${#@} >= 1 )) ; then 
       cmd=${@:$shiftn:1}
       if [ "$cmd" == "-dbg" ]; then
	       dbg=1
           shiftn=$(($shiftn+1))
	       cmd=${@:$shiftn:1}
       fi

#echo "11>>>> $cmd $*"
       shiftn=$(($shiftn+1))
       if rcmd=$(_k_bin ${FUNCNAME} $cmd); then
#echo "22>>>> $rcmd $*"
           if echo $rcmd | grep "\.k$" >& /dev/null; then
               if ! declare -F _k_$(basename "$rcmd" | sed "s/\.k$//g") >& /dev/null; then
  	           _k_load_include $rcmd
                   for ii in $(declare -F | awk ["]{print $3}["]); do
                      # make a global function
                      export -f $ii
                   done
               fi
           fi
#echo "33>>>> $rcmd $*"
           if [ "$dbg" == "1" ]; then
              logger -s "dbg> $rcmd"
              sh -x $rcmd "${@:$shiftn}"
           else
              $rcmd "${@:$shiftn}"  || return $?
           fi
       else
          echo "ERR: $rcmd"
          return 1
       fi
   fi
#set +x
}

# split for arrary
_k_k_path_split() {
    if _k_os_check osx; then
	    echo $* | sed -e $["]s|:|\\\n|g["] -e $["]s| |\\\n|g["] | sort | uniq
    else
	    echo $* |sed -e "s/:/\n/g" -e "s/ /\n/g" | sort | uniq
    fi
}

# find file["]s path
_k_find_file() {
	local name path shiftn
    shiftn=1
	name=${@:$shiftn:1}
	shiftn=$(($shiftn+1))
	path=( $(_k_k_path_split $(pwd):${@:shiftn}) )
#	path=( ${path[*]} $(_k_k_path_split ${PATH}) )
	for ((ii=0;ii<${#path[*]}; ii++)); do
        if [ -f ${path[$ii]}/$name ]; then
			echo ${path[$ii]}/$name
			return 0
	    fi
	done
    unset name
	return 1
}

_k_find_word() {
    local src
    src=$1
    shift 1
    for ii in $*; do
        [ "$src" == "$ii" ] && return 0
    done
    return 1
}

_k_debug() {
   local opt
   opt=$2
   [ -n "$_K_DEBUG" ] || _K_DEBUG=0 
   [ -n "$opt" ] || opt=1
   (( $_K_DEBUG >= $opt )) && echo "$1"
}

# load include
_k_load_include() {
    local file name _kv_path kstart shiftn include_files
    file="$1"
    [ -n "$file" -a -f "$file" ] || return 1
    include_files=$(awk ["]{if($1=="#include") print $2}["] $file | sed -e "s/<//g" -e "s/>//g")
    _k_debug "_k_load_include : all files : $include_files" "1"

    for ii in $include_files; do
       _k_debug "_k_load_include : check file : $ii" "2"
       if _kv_path=$(_k_find_file $ii $_K_BIN $_K_LIB); then
           _k_debug "_k_load_include : found file : $ii" "3"
           declare -F _k_$(basename "$_kv_path" | sed "s/\.k$//g") >& /dev/null && continue
           _k_debug "_k_load_include : load file : $ii" "3"
           _k_load_include "$_kv_path"
           _k_load "$_kv_path"

           # For Old library starter
           kstart=$(echo $(basename "$_kv_path")|sed -e "s/^k//g" -e "s/\.so$//g")
           if [ "$kstart" != ".k" ]; then
               declare -F _k_$kstart >& /dev/null && _k_$kstart
           fi
           unset kstart
       fi
       unset _kv_path
    done
    unset file 
    unset name
    return 0
}

# base stopping sample
#_k_k_close() {
#   _k_unload $(_k_k_list)
#}

# cmd sample
_k_os_check() {
  local osname osrelease
  #osname=${@:1:1}
  #osrelease=${@:2:1}
  [ "${#}" == "0" ] && return 1
#  _k_os_find
  for osname in $* ; do
     [ "$osname" == "$_kv_OS_NAME" ] && return 0
  done
  return 1
}


_k_os_find() {
  if [ -f /etc/redhat-release ]; then
    if cat /etc/redhat-release  |grep "^CentOS" > /dev/null 2>&1 ; then
      _kv_OS_NAME=centos
      _kv_OS_VERNAME=CentOS
      _kv_OS_RELEASE=$(cat /etc/redhat-release | awk ["]{print $3}["])
    else
      _kv_OS_NAME=rhel
      _kv_OS_VERNAME="Red Hat "
      _kv_OS_RELEASE=$(cat /etc/redhat-release | awk ["]{print $7}["])
    fi
  elif [ -f /etc/SuSE-release ]; then
    _kv_OS_NAME=sles
    _kv_OS_VERNAME="SuSE Linux "
    _kv_OS_PATCH=$(cat /etc/SuSE-release | grep PATCHLEVEL | awk ["]{print $3}["])
    [ -n "$_kv_OS_PATCH" ] && _kv_OS_RELEASE=$(cat /etc/SuSE-release | grep VERSION | awk ["]{print $3}["]).$OS_PATCH || _kv_OS_RELEASE=$(cat /etc/SuSE-release | grep VERSION | awk ["]{print $3}["])
  elif [ "$(uname -s)" == "Darwin" ]; then
    _kv_OS_NAME=osx
    _kv_OS_VERNAME=$(sw_vers -productName)
    _kv_OS_RELEASE=$(sw_vers -productVersion)
  elif [ -f /system/bin/am -a -f /system/bin/pm ]; then
    _kv_OS_NAME=android
    _kv_OS_VERNAME=
    _kv_OS_RELEASE=
  elif [ -f /etc/issue ]; then
    _kv_OS_NAME=ubuntu
    _kv_OS_VERNAME=$(cat /etc/issue | awk ["]{print $1;}["])
    _kv_OS_RELEASE=$(cat /etc/issue | awk ["]{print $2;}["])
  else
    echo "UnknownOS"
    return 1
  fi
  export _kv_OS_NAME _kv_OS_VERNAME _kv_OS_RELEASE
}

_k_os_print() {
#  _k_os_find
  echo "$_kv_OS_NAME $_kv_OS_VERNAME $_kv_OS_RELEASE"
}

_k_real_path() {
    if [ -d "$1" ]; then
        cd "$1" && pwd -P
    else 
        cd $(dirname "$1") && pwd -P
    fi
}

_k_readlink() {
    local opts
    opts=("$@")
    _k_opt -n 0 0 "${opts[@]}" && no_newline="-n"
    _k_opt -s 0 0 "${opts[@]}" && slient="-s"
    _k_opt -f 0 0 "${opts[@]}" && canonicalize="-f"
    file=$(_k_opt_end 1 "${opts[@]}")
    [ ! -n "$file" -o "$file" == "-bash" -o "$file" == "-sh" ] && return 1
    if _k_os_check osx; then
       if [ "$canonicalize" == "-f" ]; then
           [ "$slient" == "-s" ] && \
              echo $no_newline $(_k_real_path "$file")/$(readlink "$file" || ([ -d "$file" ] || basename "$file")) 2>/dev/null || \
              echo $no_newline $(_k_real_path "$file")/$(readlink "$file" || ([ -d "$file" ] || basename "$file"))
       else
           if [ "$slient" == "-s" ]; then
               readlink $no_newline "$file"  2>/dev/null
               return $?
           else
               readlink $no_newline "$file"
               return $?
           fi
       fi
    else
       readlink $canonicalize $no_newline $slient "$file"
       return $?
    fi
}

_k_make_temp() {
    local name fname dir
    name=$(basename "${@:1:1}" | sed "s/\.k$//g")
    dir=$(dirname "${@:1:1}")
    fname=$dir/${name}.k
    if [ -f $fname ]; then
        echo "Exist $fname"
        _k_exit 1
    fi 

    echo "########################################################################
# Copyright (c) CEP Research Institude, All rights reserved. Since 2008
#    Kage Park <kagepark@cep.kr>
#\$version\$:0.1.0
# Created at $(date)
# Description : 
########################################################################
KTAG=\".k\"
# _k_  : Kage function
# _kv_  : Kage variable

# Global library
#include k.k

_k_${name}_help() {
  #echo \"$name - v\$(grep \"^#\\\$version\\\$:\" \$0 | awk -F: ["]{print \$2}["])
  echo \"

\$(basename \$0) [<opt> [<input>] ]
  \$(_k_version_info \$0)

  --help : help
  \"
  _k_exit 1
}

# base starting sample
# _k_opt <find> <num> <ro> <input options>

# <num>
#   all      : get whole value between option (start -)
#   #        : get values of # after finded option (default 1)

# <ro>
#  ro=0      : return <value> (default)
#  ro=1      : return <remained opt>
#  ro=2      : return <value>|<remained opt>

# example for cmd is sample
_k_${name}() {
   local cmd rcmd opt get_val
   echo \$1 | grep \"^-\" >& /dev/null || cmd=\$1
   declare -F \${FUNCNAME}_\${cmd} >& /dev/null && shift 1

   opt=(\"\$@\")

#   get_end_val=$(_k_opt_end 1 \"\${opt[@]}\")

   if _k_opt --help 0 0 \"\${opt[@]}\" >/dev/null; then
       _k_${name}_help
#   elif get_val=\$(_k_opt -t 1 0 \"\${opt[@]}\"); then
#      _k_${name}_sample \$get_val || return 1
#or
#   elif _k_opt -t 2 0 \"\${opt[@]}\" >& /dev/null; then
#      _k_${name}_sample \"\${opt_out[@]}\" || return 1
   else
      if declare -F \${FUNCNAME}_\${cmd} >& /dev/null; then
           \${FUNCNAME}_\${cmd} \"\${opt[@]}\"
      else
      #     <command> \"\${opt[@]}\"
      #     or
            echo \"Unknown option\"
            _k_exit 1
      fi
   fi
}

#_k_${name}_sample () {
#  loading library for _k_${name}_sample()
#  _k_load_include <require package name> <req. pkg name2> ... 
#  local opts
#  opts=(\"\$@\")
#  example  for \"k ${name} sample\"
#}

" > $fname
    
    chmod +x $fname
}

#_k_opt_find <find> <opts>
_k_opt_find() {
  local z opts find n
  find=${@:1:1}
  opts=("${@:2}")
  [ $# -lt 2 ] && error_return "_k_opt <find> <opts>"
  for ((z=0; z<${#opts[@]}; z++)); do 
    if [ "$find" == "${opts[$z]}" ]; then
      echo "$z"
      return 0
    fi
  done
  return 1
}

#_k_opt_end <num> <opts>
_k_opt_end() {
   local opts num get total
   num=${@:1:1}
   opts=("${@:2}")
   total=$((${#opts[@]}-1))
   opt_out=()
   if [ ! -n "$num" ]; then
       echo "${opts[@]}"
       return 0
   elif [ "$num" == "all" -o "$num" == "0" ]; then
       fnum=0
   elif (($num>=1)); then
       fnum=$(($total-$num+1))
   fi
   for ((z=$total; z >= $fnum; z--)); do
       echo "${opts[$z]}" | grep "^-" >& /dev/null && break 
       [ "${get[*]}" ] && get=("${opts[$z]}" "$get") || get=("${opts[$z]}");
   done
   if [ -n "${get[*]}" ]; then
       echo "${get[*]}"
       opt_out=("${get[@]}")
       export opt_out
       return 0
   else
       return 1
   fi
}

#_k_opt <find> <num> <ro> <opts>
# <num> : print how many values for found option
#   0 : find and return 0
#   1 : find and print one value and return 0
#   # : find and print # of values and return 0
#  all: find all value until start -
# <ro> : return output
#   0  : print <value> & opt_out=(<value>)
#   1  : print <remained options> & opt_out=(<remained options>)
#   2  : print <value>|<remained options> & opt_out=(<value> | <remained options>)
#   3  : print <value> & opt_out=(<remained options>)
#   4  : opt_out=(<remained options>)

_k_opt() {
    local input find num get ro opts
    find="${@:1:1}"
    num="${@:2:1}"
    ro="${@:3:1}"
    opts=( "${@:4}" )

    opt_out=()

    [ "$find" == "--help" ] && num=0
    [ -n "$num" ] || num=1
    num_input=${#opts[@]}
    for ((i=0;i<$num_input;i++)); do
       if [ "${opts[$i]}" == "$find" ]; then
          unset opts[$i]
          if [ "$num" == "0" ]; then
             get[0]="help"
             break
          elif [ "$num" == "all" ]; then
             fnum=$(($num_input-1))
          elif (($num>0)); then
             fnum=$(($num+$i))
             (($fnum>=$num_input)) && return 1
          fi

          for ((z=$(($i+1)); z <=$fnum; z++)); do
                 if echo ${opts[$z]} | grep "^-" >/dev/null; then
                    [ "$num" == "all" ] && break || return 1
                 else
                    [ -n "${get[*]}" ] && get=("${get[@]}" "${opts[$z]}") || get=("${opts[$z]}")
                    unset opts[$z]
                 fi
          done
       fi
    done

    if [ -n "${get[*]}" ]; then
          if [ "$ro" == "1" ]; then
              opts=("${opts[@]}")
              echo "${opts[@]}"
              opt_out=("${opts[@]}")
          elif [ "$ro" == "2" ]; then
              opts=("${opts[@]}")
              echo "${get[@]}|${opts[@]}"
              opt_out=("${get[@]}" "|" "${opts[@]}")
          elif [ "$ro" == "3" ]; then
              opts=("${opts[@]}")
              echo "${get[@]}"
              opt_out=("${opts[@]}")
          elif [ "$ro" == "4" ]; then
              opts=("${opts[@]}")
              opt_out=("${opts[@]}")
          else
              if [ "${get[*]}" != "help" ]; then
                   echo "${get[@]}"
                   opt_out=("${get[@]}")
              fi
          fi
          export opt_out
          return 0
    else
          return 1
    fi
}

_k_setup() {
    local base_path
    base_path="$1"
    if [ ! -n "$base_path" ]; then
          echo "k setup <kc home path>"
          _k_exit 1
    fi
    if [ ! -f ${base_path}/kbin/k.k ]; then
        echo "KC file not found"
        _k_exit 1
    fi
    if [ -n "$_K_HOME" ]; then
        echo "Found KC Environment"
        _k_exit 0
    else
        [ -L ${base_path}/kbin/k ] || ( cd ${base_path}/kbin && ln -s k.k k )

        echo "
## KC Environment >>>
export _K_HOME=$base_path
export _K_LIB=\${_K_HOME}/klib
export _K_BIN=\${_K_HOME}/kbin
export _K_ETC=\${_K_HOME}/ketc
export PATH=\${_K_BIN}:\${PATH} 
## KC Environment <<< " >> ~/.bashrc

        echo "
  Setup KC Environment to ~/.bashrc
  Please reload environment or logout and login again
        "
        return 0
    fi
}

k() {
    [ "$(basename "$(_k_readlink -f "$0")")" == "k.k" ] || _k_ai_q "$@"
}

_k_find_os() {
    _k_os_find $*
}

_k_shell_version() {
    sh --version | grep version |grep release | awk ["]{print $4}["] | awk -F\( ["]{print $1}["]
}

_k_shell_check() {
    local support_version=4.0 curr_version chk_ver
    curr_version=$(_k_shell_version)
    chk_ver=$(echo "$curr_version
$support_version" | _k_sort -V | tail -n1)
    [ "$chk_ver" == "$support_version" ] && return 1 || return 0
}

_k_function_list() {
    compgen -A function
}

_k_load_all() {
   if [ -n "$_K_BIN" ]; then
      _k_version
      comment=0
      if [ $comment != 1 ]; then
       for ii in $(find $_K_BIN -name "*.k"); do
         basename $ii | grep "^_" > /dev/null && continue
         echo "Load $ii..."
         grep "^if \[ \"\$(basename \$0)\"" $ii >& /dev/null && source $ii 2>/dev/null
       done
      fi

      if [ -n "$_K_LIB" ]; then
         for ii in $(find $_K_LIB -name "k*.so"); do
            basename $ii | grep -e "^_" -e "klib.so" > /dev/null && continue
            echo "Load $ii..."
            source $ii 2>/dev/null
         done
      else
         echo "_K_LIB not found"
      fi
   else
      echo "_K_BIN not found"
   fi
}

_k_view_kshell() {
   local name
   name=$1
   [ -n "$name" ] || return 1
   if declare -F _k_$name >& /dev/null; then
      name=_k_$name
   elif declare -F $name >& /dev/null; then
      name=$name
   else
      return 1
   fi
   declare -f $name
}

_k_vi_load() {
    local file
    file=$1
    [ -f "$file" ] || return 1
    if source $file; then
        rm -f $file
        return 0
    else
        echo "Anykey to continue...";
        read x;
        return 1
    fi
}

_k_vi_kshell() {
    local aa;
    aa=$@;
    if [ "${aa[0]}" == "--help" ]; then
        echo "${FUNCNAME} <func name>";
        return;
    fi;
    _k_view_kshell $* > /tmp/_k_vi.tmp || \
    echo "_k_${aa[0]}() {
    version=0.1.0
    desc=\"Copyright (c) CEP Research Institude, All rights reserved. Since 2008
Created at $(date)
Description : _k_${aa[0]}
\"

    func_help=\"\${FUNCNAME} [<opt> [<input>] ]
  version: \$version
  --help : help
  --desc : view description
\"
    if [ \"\$1\" == \"--help\" ]; then
        echo \"\$func_help\"
        return 0
    elif [ \"\$1\" == \"--desc\" ]; then
        echo \"\$desc\"
        return 0
    fi
    # Code here
}" > /tmp/_k_vi.tmp

    while [ 1 ]; do
       get_ver_str="$(grep "version=" /tmp/_k_vi.tmp)"
       new_ver=$(echo $get_ver_str | awk -F= ["]{print $2}["] | awk -F. ["]{printf "%s.%s.%s",$1,$2,$3+1}["])
#echo "sed \"s/$get_ver_str/    version=$new_ver/g\" /tmp/_k_vi.tmp > /tmp/_k_vi.tmp~"
#sleep 10
       sed "s/$get_ver_str/    version=$new_ver;/g" /tmp/_k_vi.tmp > /tmp/_k_vi.tmp~
       mv /tmp/_k_vi.tmp~ /tmp/_k_vi.tmp
       vim /tmp/_k_vi.tmp
       _k_vi_load /tmp/_k_vi.tmp && return 0
    done
}

_k_edit_kshell() {
    _k_vi_kshell $*
}

_k_diff_kshell() {
    local file func_list
    file=$1
    [ -n "$file" ] || return 1
    [ -f "$file" ] || return 1
    
    [ -f /tmp/_k_diff_p_ksell.tmp ] && rm -f /tmp/_k_diff_p_ksell.tmp
    [ -f /tmp/_k_diff_ksell.tmp ] && rm -f /tmp/_k_diff_ksell.tmp

    func_list=$(grep "^_k_" "$file" | awk -F\( ["]{print $1}["])
    if [ -n "$func_list" ]; then
        compare_func_list=$(for tt in $func_list; do
                declare -F $tt >& /dev/null && echo $tt
            done)
        if [ -n "$compare_func_list" ]; then
            for tt in $compare_func_list; do
                 declare -f $tt >> /tmp/_k_diff_p_ksell.tmp
            done

            ( source $file;
              for tt in $compare_func_list; do
                 declare -f $tt >> /tmp/_k_diff_ksell.tmp
              done
            )
            diff -up /tmp/_k_diff_p_ksell.tmp /tmp/_k_diff_ksell.tmp | sed -e "s#/tmp/_k_diff_p_ksell.tmp#Existing function in Memory#g" -e "s#/tmp/_k_diff_ksell.tmp#$file#g"
            [ -f /tmp/_k_diff_p_ksell.tmp ] && rm -f /tmp/_k_diff_p_ksell.tmp
            [ -f /tmp/_k_diff_ksell.tmp ] && rm -f /tmp/_k_diff_ksell.tmp
        else
            echo "$file is newer function group"
        fi
    else
        echo "$file is not kshell type function group"
    fi
}

_k_ai_q() {
    local q qm cmd_end=0 qcmd
    qm=(["].["] ["]?["] ["]!["])
    q=("$@")
    qcmd="_k_"
    for ii in ${!q[@]}; do
#echo ">$ii: ${q[$ii]}"
        echo "${q[$ii]}" | grep "^#" >& /dev/null && continue
        if echo "${q[$ii]}" | grep -e "\.$" -e "\?$" -e "\!$"  >& /dev/null; then 
            qcmd=$qcmd$(printf "%s" "${q[$ii]}" | sed -e "s/\.$//g" -e "s/\!$//g" -e "s/\?$//g")
            cmd_end=1
            break
        else
            qcmd=$qcmd$(printf "%s" "${q[$ii]}_")
        fi
    done
    if [ "$cmd_end" == "1" ]; then
#echo ">> $ii : ${@:$(($ii+2))} => $qcmd ${@:$(($ii+2))}"
        if declare -F $qcmd >& /dev/null; then
            $qcmd "${@:$(($ii+2))}"
            return $?
        else
            _k_k $(echo $qcmd | sed "s/^_k_//g") "${@:$(($ii+2))}"
            return $?
        fi
    else
        _k_k "$@"
        return $?
    fi
}


[ "$1" == "--help" ] && _k_k_help
_k_ai_q "$@" || _k_exit $?


name: test
value:
########################################################################
# Copyright (c) CEP Research Institude, All rights reserved. Since 2008
#    Kage Park <kagepark@cep.kr>
#$version$:0.1.0
# Created at Fri Aug 19 17:41:28 CDT 2016
# Description : 
########################################################################
KTAG=".k"
# _k_  : Kage function
# _kv_  : Kage variable

# Global library
#include k.k

_k_test_help() {
  #echo "test - v$(grep "^#\$version\$:" $0 | awk -F: ["]{print $2}["])
  echo "

$(basename $0) [<opt> [<input>] ]
  $(_k_version_info $0)

  --help : help
  "
  _k_exit 1
}

# base starting sample
# _k_opt <find> <num> <ro> <input options>

# <num>
#   all      : get whole value between option (start -)
#   #        : get values of # after finded option (default 1)

# <ro>
#  ro=0      : return <value> (default)
#  ro=1      : return <remained opt>
#  ro=2      : return <value>|<remained opt>

# example for cmd is sample
_k_test() {
   local cmd rcmd opt get_val
   echo $1 | grep "^-" >& /dev/null || cmd=$1
   declare -F ${FUNCNAME}_${cmd} >& /dev/null && shift 1

   opt=("$@")

   if _k_opt --help 0 0 "${opt[@]}" >/dev/null; then
       _k_test_help
   elif get_val=$(_k_opt -t 1 0 "${opt[@]}"); then
      _k_test_sample $get_val || return 1
   else
      if declare -F ${FUNCNAME}_${cmd} >& /dev/null; then
           ${FUNCNAME}_${cmd} "${opt[@]}"
      else
            echo "Unknown option"
            _k_exit 1
      fi
   fi
}

_k_test_sample () {
  local opts
  opts=("$@")
  echo ${opts[@]}
}


