#! /bin/sh
# this scrip write by Clang at 2018-01-13
# This script is meant for quick & easy install via:
#   'sh -c "$(curl -sSL http://firmware.koolshare.cn/shell/tmux/tmux.sh)"'
# or:
#   'sh -c "$(wget --no-check-certificate -qO- http://firmware.koolshare.cn/shell/tmux/tmux.sh)"'
#   'wget --no-check-certificate http://firmware.koolshare.cn/shell/tmux/tmux.sh -qO /tmp/tmux.sh; sh /tmp/tmux.sh'
#
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
fun_shell_update() {
    echo "========== Update tmux shell =========="
    remote_shell_version=`wget --no-check-certificate -qO- ${shell_download} | sed -n '/'^version'/p' | cut -d\" -f2`
    if [ ! -z ${remote_shell_version} ]; then
        if [ "${version}"x != "${remote_shell_version}"x ];then
            if ! wget --progress=bar:force --prefer-family=IPv4 --no-check-certificate ${shell_download} -O $0; then
                printf "${RED}Failed to download shell file!${NORMAL}\n"
            else
                printf "${GREEN}shell Update successfully !!!${NORMAL}\n"
            fi
        else
            printf "${GREEN}shell no need to update !!!${NORMAL}\n"
        fi
        exit 0
    fi
}
version="4.4"
tmux_ver="2.6"
libevent_ver="2.1.8"
shell_url="http://firmware.koolshare.cn/shell"
shell_download="${shell_url}/tmux/tmux.sh"
conf_download="${shell_url}/tmux/tmux.conf"
conf_tpm_download="${shell_url}/tmux/tmux-tpm.conf"
libevent_download="${shell_url}/tmux/libevent-${libevent_ver}-stable.tar.gz"
tmux_download="${shell_url}/tmux/tmux-${tmux_ver}.tar.gz"
shell_install_path="/usr/local/bin/tmux.sh"
strPath=`pwd`
fun_set_color() {
    # Use colors, but only if connected to a terminal, and that terminal
    # supports them.
    if which tput >/dev/null 2>&1; then
        ncolors=$(tput colors)
    fi
    if [ -t 1 ] && [ -n "$ncolors" ] && [ "$ncolors" -ge 8 ]; then
        BLACK_B="$(tput setab 0)"
        RED_B="$(tput setab 1)"
        GREEN_B="$(tput setab 2)"
        YELLOW_B="$(tput setab 3)"
        BLUE_B="$(tput setab 4)"
        MAGENTA_B="$(tput setab 5)"
        CYAN_B="$(tput setab 6)"
        WHITE_B="$(tput setab 7)"
        BLACK="$(tput setaf 0)"
        RED="$(tput setaf 1)"
        GREEN="$(tput setaf 2)"
        YELLOW="$(tput setaf 3)"
        BLUE="$(tput setaf 4)"
        MAGENTA="$(tput setaf 5)"
        CYAN="$(tput setaf 6)"
        WHITE="$(tput setaf 7)"
        BOLD="$(tput bold)"
        NORMAL="$(tput sgr0)"
    else
        BLACK_B=""
        RED_B=""
        GREEN_B=""
        YELLOW_B=""
        BLUE_B=""
        MAGENTA_B=""
        CYAN_B=""
        WHITE_B=""
        BLACK=""
        RED=""
        GREEN=""
        YELLOW=""
        BLUE=""
        MAGENTA=""
        CYAN=""
        WHITE=""
        BOLD=""
        NORMAL=""
    fi
}
command_exists() {
    command -v "$@" > /dev/null 2>&1
}
Get_Dist_Name() {
    systemPackage=''
    if grep -Eqi "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
        systemPackage='yum'
    elif grep -Eqi "Red Hat Enterprise Linux Server" /etc/issue || grep -Eq "Red Hat Enterprise Linux Server" /etc/*-release; then
        systemPackage='yum'
    elif grep -Eqi "Aliyun" /etc/issue || grep -Eq "Aliyun" /etc/*-release; then
        systemPackage='yum'
    elif grep -Eqi "Fedora" /etc/issue || grep -Eq "Fedora" /etc/*-release; then
        systemPackage='yum'
    elif grep -Eqi "Amazon Linux AMI" /etc/issue || grep -Eq "Amazon Linux AMI" /etc/*-release; then
        systemPackage='yum'
    elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
        systemPackage='apt'
    elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
        systemPackage='apt'
    elif grep -Eqi "Raspbian" /etc/issue || grep -Eq "Raspbian" /etc/*-release; then
        systemPackage='apt'
    elif grep -Eqi "Deepin" /etc/issue || grep -Eq "Deepin" /etc/*-release; then
        systemPackage='apt'
    elif grep -Eqi "Mint" /etc/issue || grep -Eq "Mint" /etc/*-release; then
        systemPackage='apt'
    else
        systemPackage='unknow'
    fi
}
check_sys() {
    local value=$1
    if [ "$value"x = "$systemPackage"x ]; then
        return 0
    else
        return 1
    fi
}
check_os() {
    Get_Dist_Name
    if [ "${systemPackage}"x = "unknow"x ]; then
        printf "${YELLOW}Error: Unable to get Linux distribution name, or do NOT support the current distribution.${NORMAL}\n"
        exit
    fi
}
check_tmux() {
    tmux -V >/dev/null 2>&1
    tmux_flag=$?
    git version>/dev/null 2>&1
    git_flag=$?
    if [ ${tmux_flag} -ge 1 ] || [ ${git_flag} -ge 1 ]; then
        printf "${BLUE}+ Install support packs ...${NORMAL}\n"
        user="$(id -un 2>/dev/null || true)"
        sh_c='sh -c'
        if [ "$user" != 'root' ]; then
            if command_exists sudo; then
                sh_c='sudo -E sh -c'
            elif command_exists su; then
                sh_c='su -c'
            else
                cat >&2 <<-'EOF'
                Error: this installer needs the ability to run commands as root.
                We are unable to find either "sudo" or "su" available to make this happen.
EOF
                exit 1
            fi
        fi
        (
            set -e
            if check_sys yum; then
                ( set -x; $sh_c 'sleep 3; yum -y install libevent-devel ncurses-devel git gcc' )
            elif check_sys apt; then
                ( set -x; $sh_c 'sleep 3; apt-get update; apt-get install -y --no-install-recommends build-essential libncurses5-dev git' ) || true
            fi
        )
        libevent_main_ver="$(echo ${libevent_ver} | cut -c1-3)"
        if [ ! -L /usr/local/lib/libevent-${libevent_main_ver}.so.6 ]; then
            printf "${BLUE}+ Build libevent ...${NORMAL}\n"
            cd /tmp
            printf "${CYAN}  Download libevent-${libevent_ver}${NORMAL}\n"
            if ! wget --progress=bar:force --prefer-family=IPv4 --no-check-certificate ${libevent_download}; then
                printf "${RED}Failed to download libevent-${libevent_ver}-stable.tar.gz file!${NORMAL}\n"
                exit 1
            fi
            (
                set -e
                set -x
                tar xzf libevent-${libevent_ver}-stable.tar.gz
                cd libevent-${libevent_ver}-stable
                $sh_c 'sleep 3; ./configure'
                $sh_c 'sleep 3; make && make install'
            )
            if [ ! -L /usr/local/lib/libevent-${libevent_main_ver}.so.6 ]; then
                printf "${RED}libevent install failed!${NORMAL}\n"
                $sh_c "sleep 3; cd /tmp; rm -fr libevent-${libevent_ver}-stabl*"
                exit 1
            fi
            ( set -x; $sh_c "sleep 3; cd /tmp; rm -fr libevent-${libevent_ver}-stabl*" )
            if [ `grep -L "/lib"    '/etc/ld.so.conf'` ]; then
                ( set -x; $sh_c 'sleep 3; echo "/lib" >> /etc/ld.so.conf')
            fi
            if [ `grep -L '/usr/lib'    '/etc/ld.so.conf'` ]; then
                ( set -x; $sh_c 'sleep 3; echo "/usr/lib" >> /etc/ld.so.conf' )
                #echo "/usr/lib/openssl/engines" >> /etc/ld.so.conf
            fi
            if [ -d "/usr/lib64" ] && [ `grep -L '/usr/lib64'    '/etc/ld.so.conf'` ]; then
                ( set -x; $sh_c 'sleep 3; echo "/usr/lib64" >> /etc/ld.so.conf' )
                #echo "/usr/lib64/openssl/engines" >> /etc/ld.so.conf
            fi
            if [ `grep -L '/usr/local/lib'    '/etc/ld.so.conf'` ]; then
                ( set -x; $sh_c 'sleep 3; echo "/usr/local/lib" >> /etc/ld.so.conf' )
            fi
            ( set -x; $sh_c 'sleep 3; ldconfig' )
        fi
        printf "${BLUE}+ Build Tmux ...${NORMAL}\n"
        printf "${CYAN}  Download tmux-${tmux_ver}${NORMAL}\n"
        if ! wget --progress=bar:force --prefer-family=IPv4 --no-check-certificate ${tmux_download}; then
            printf "${RED}Failed to download tmux-${tmux_ver}.tar.gz file!${NORMAL}\n"
            exit 1
        fi
        (
            set -e
            set -x
            tar zxf tmux-${tmux_ver}.tar.gz
            cd tmux-${tmux_ver}
            $sh_c "sleep 3; CFLAGS="-I/usr/local/include" LDFLAGS="-L/usr/local/lib" ./configure"
            $sh_c 'sleep 3; make && make install'
            $sh_c 'sleep 3; cd /tmp; rm -fr tmux-*'
        )
        ( set -x; $sh_c "sleep 3; wget --progress=bar:force --prefer-family=IPv4 --no-check-certificate ${shell_download} -qO ${shell_install_path}" )
        if [ `grep -L 'check_tmux' "${shell_install_path}"` ]; then
            printf "${RED}Tmux Shell download failed!${NORMAL}\n"
            exit 1
        else
            [ ! -x ${shell_install_path} ] && ( set -x; $sh_c "sleep 3; chmod +x ${shell_install_path}" )
            if [ ! -L /usr/local/bin/win ] && [ -x "${shell_install_path}" ]; then
                ( set -x; $sh_c "sleep 3; ln -sf ${shell_install_path} /usr/local/bin/win" )
            fi
        fi
        tmux -V >/dev/null 2>&1
        if [ $? -lt 1 ] && [ -x "${shell_install_path}" ] && [ -L /usr/local/bin/win ];then
            printf "${BLUE}TMUX install success!${NORMAL}\n"
        else
            printf "${RED}TMUX install failed!${NORMAL}\n"
            exit 1
        fi
        [ ! -f $HOME/.tmux.conf ] && fun_config
    fi
}
# config
fun_config() {
    printf "${BLUE}+ config tmux!!!${NORMAL}\n"
    en_tpm="n"
    if [ "${arg1}"x = "config"x ] || [ "${arg1}"x = "c"x ] || [ "${arg1}"x = "-c"x ] || [ "${arg1}"x = "--c"x ] || [ "${arg1}"x = "conf"x ]; then
        printf "${YELLOW}enable Tmux Plugin Manager? ${NORMAL}"
        stty erase '^H' && read -p "[Y/n]:" en_tpm
        case "${en_tpm}" in
            [nN]|[nN][oO])
                en_tpm="n"
                ;;
            *)
                en_tpm="y"
        esac
    fi
    if [ "${en_tpm}"x = "y"x ]; then
        printf "${BLUE}+ enable Tmux Plugin Manager${NORMAL}\n"
        if [ ! -s ~/.tmux/plugins/tpm/README.md ]; then
            git clone --depth=1 https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm
            if grep -q "Tmux Plugin Manager" ~/.tmux/plugins/tpm/README.md; then
                printf "${GREEN}+ Download Tmux Plugin Manager success!${NORMAL}\n"
            else
                printf "${RED}+ Download Tmux Plugin Manager failed!${NORMAL}\n"
            fi
        fi
        if [ ! -s ~/.tmux/plugins/tmux-sensible/README.md ]; then
            git clone --depth=1 https://github.com/tmux-plugins/tmux-sensible ~/.tmux/plugins/tmux-sensible
            if grep -q "Tmux sensible" ~/.tmux/plugins/tmux-sensible/README.md; then
                printf "${GREEN}+ Download Tmux sensible success!${NORMAL}\n"
            else
                printf "${RED}+ Download Tmux sensible failed!${NORMAL}\n"
            fi
        fi
        if [ ! -s ~/.tmux/plugins/tmux-resurrect/README.md ]; then
            git clone --depth=1 https://github.com/tmux-plugins/tmux-resurrect ~/.tmux/plugins/tmux-resurrect
            if grep -q "Tmux Resurrect" ~/.tmux/plugins/tmux-resurrect/README.md; then
                printf "${GREEN}+ Download Tmux Resurrect success!${NORMAL}\n"
            else
                printf "${RED}+ Download Tmux Resurrect failed!${NORMAL}\n"
            fi
        fi
        wget --progress=bar:force --prefer-family=IPv4 --no-check-certificate ${conf_tpm_download} -O $HOME/.tmux.conf
    else
        wget --progress=bar:force --prefer-family=IPv4 --no-check-certificate ${conf_download} -O $HOME/.tmux.conf
    fi
    if grep -q "127F95F1048BC447" $HOME/.tmux.conf; then
        printf "${GREEN}+ config tmux success!${NORMAL}\n"
    else
        printf "${RED}+ config tmux failed!${NORMAL}\n"
    fi
}
fun_show_all_session() {
    #clear
    tmux ls
}
fun_new_session() {
    session_name=""
    stty erase '^H' && read -p "Please input new session name:" session_name
    if [ "${session_name}"x = ""x ]; then
        echo "Error: You must input new session name!!"
        exit 1
    fi
    tmux -u new -s ${session_name}
}
fun_return_session_id() {
    session_id=""
    stty erase '^H' && read -p "Please input session id:" session_id
    if [ "${session_id}"x = ""x ]; then
        echo "Error: You must input session id!!"
        exit 1
    fi
    tmux attach -t ${session_id}
}
fun_return_session() {
    if [ -z "${1}" ]; then
        tmux attach
    else
        tmux attach -t ${1}
    fi
}
fun_kill_session() {
    if [ -z "${1}" ]; then
        fun_show_all_session
        session_id=""
        stty erase '^H' && read -p "Please input session id:" session_id
        if [ "${session_id}"x = ""x ]; then
            echo "Error: You must input session id!!"
            exit 1
        fi
    else
        session_id=${1}
    fi
    tmux kill-session -t ${session_id}
}
fun_start_tmux() {
    tmux -u
}
fun_hotkey(){
    strLine1="+-------------------------------------------------------------------------------------+"
    strLine2="+--------------------------+---------------+------------------------------------------+"
    strLine3="+--------------+-----------+---------------+--------------+---------------------------+"
    strLine4="+--------------+---------------------------+--------------+---------------------------+"
    strLine5="+--------------+---------------------------+--------------+---------------------------+"
    printf "${strLine1}\n"
    printf "|                                 ${COLOR_GREEN}TMUX  Hotkey  Help${NORMAL}                                  |\n"
    printf "${strLine2}\n"
    printf "|    More Hotkey: ${YELLOW}^a${NORMAL}+${MAGENTA}?${NORMAL}     |   ${YELLOW}^${NORMAL} = ${MAGENTA}Ctrl${NORMAL}    |   ${COLOR_RED}Warning : ${NORMAL}Hotkey Case sensitive.       |\n"
    printf "${strLine3}\n"
    printf "|   [Hotkey]   |       [Description]       |   [Hotkey]   |       [Description]       |\n"
    printf "${strLine4}\n"
    printf "| ${YELLOW}^a${NORMAL}+${MAGENTA}s${NORMAL}         | Change Session list       | ${YELLOW}^a${NORMAL}+${MAGENTA}d${NORMAL}         | detach-client             |\n"
    printf "${strLine5}\n"
    printf "| ${YELLOW}^a${NORMAL}+${MAGENTA}c${NORMAL}         | new-window                | ${YELLOW}^a${NORMAL}+${MAGENTA}k${NORMAL}         | kill-window               |\n"
    printf "${strLine5}\n"
    printf "| ${YELLOW}^a${NORMAL}+${MAGENTA}[0-9]${NORMAL}     | select-window             | ${YELLOW}^a${NORMAL}+${MAGENTA}A${NORMAL}         | rename-window             |\n"
    printf "${strLine5}\n"
    printf "| ${YELLOW}^a${NORMAL}+${MAGENTA}n${NORMAL}         | next-window               | ${YELLOW}^a${NORMAL}+${MAGENTA}t${NORMAL}         | clock-mode                |\n"
    printf "${strLine5}\n"
    printf "| ${YELLOW}^a${NORMAL}+${MAGENTA}-${NORMAL}         | split-window horizontal   | ${YELLOW}^a${NORMAL}+${MAGENTA}|${NORMAL} or ${MAGENTA}\\ ${NORMAL}   | split-window vertical     |\n"
    printf "${strLine5}\n"
    printf "| ${YELLOW}^a${NORMAL}+${MAGENTA}{Left}${NORMAL}    | select-pane left          | ${YELLOW}^a${NORMAL}+${MAGENTA}{Right}${NORMAL}   | select-pane right         |\n"
    printf "${strLine5}\n"
    printf "| ${YELLOW}^a${NORMAL}+${MAGENTA}{Up}${NORMAL}      | select-pane up            | ${YELLOW}^a${NORMAL}+${MAGENTA}{Down}${NORMAL}    | select-pane down          |\n"
    printf "${strLine5}\n"
    printf "| ${YELLOW}^a${NORMAL}+${MAGENTA}^o${NORMAL}        | rotate-pane               | ${YELLOW}^a${NORMAL}+${MAGENTA}TAB${NORMAL}       | select-pane               |\n"
    printf "${strLine5}\n"
}
fun_main(){
    echo "============================================================="
    echo "which do you want to?"
    printf "${GREEN}a${NORMAL}. show all session\n"
    printf "${GREEN}b${NORMAL}. new session\n"
    printf "${GREEN}c${NORMAL}. return session id\n"
    printf "${GREEN}d${NORMAL}. return session\n"
    printf "${GREEN}h${NORMAL}. Help\n"
    printf "${GREEN}k${NORMAL}. kill session\n"
    printf "${GREEN}s${NORMAL}. start tmux\n"
    printf "${GREEN}0${NORMAL}. Exit\n"
    echo ""
    stty erase '^H' && read -p "Please input: " num
    echo ""

    case "$num" in
        [aA] ) (fun_show_all_session);;
        [bB] ) (fun_new_session);;
        [cC] ) (fun_show_all_session && fun_return_session_id);;
        [dD] ) (fun_return_session);;
        [hH] ) (fun_hotkey);;
        [kK] ) (fun_kill_session);;
        [sS] ) (fun_start_tmux);;
        [0] ) (exit 0);;
        *) printf "${RED} Input Error,Exit! ${NORMAL} \n" && echo "" && exit 0 ;;
    esac
}
fun_set_color
arg1=$(echo $1 | tr '[A-Z]' '[a-z]')
arg2=$(echo $2 | tr '[A-Z]' '[a-z]')
check_os
check_tmux
# [  -z ${arg1} ]
case "${arg1}" in
    start|s|-s|--s)
        fun_start_tmux
        ;;
    list|l|ls|-ls|l|-l|--l)
        fun_show_all_session
        ;;
    new|n|-n|--n)
        fun_new_session
        ;;
    restore|return|r|-r|--r)
        fun_return_session ${arg2}
        ;;
    kill-session|kill|-k|--k|k)
        fun_kill_session ${arg2}
        ;;
    config|c|-c|--c|conf)
        fun_config
        ;;
    update|u|-u|--u|up)
        fun_shell_update
        ;;
    help|-help|--help|h|-h|--h|?)
        fun_hotkey
        ;;
    menu|m|-m|--m)
        fun_main
        ;;
    *)
        fun_hotkey
        ;;
esac
exit
