#!/bin/bash

# This script will install the necessary configuration for zsh and bash completion
#
# Sebastian Bachmann <hello@reox.at>, 2016

ask() {
    # http://djm.me/ask
    local prompt default REPLY

    while true; do

        if [ "${2:-}" = "Y" ]; then
            prompt="Y/n"
            default=Y
        elif [ "${2:-}" = "N" ]; then
            prompt="y/N"
            default=N
        else
            prompt="y/n"
            default=
        fi

        # Ask the question (not using "read -p" as it uses stderr not stdout)
        echo -n "$1 [$prompt] "

        # Read the answer (use /dev/tty in case stdin is redirected from somewhere else)
        read REPLY </dev/tty

        # Default?
        if [ -z "$REPLY" ]; then
            REPLY=$default
        fi

        # Check if the reply is valid
        case "$REPLY" in
            Y*|y*) return 0 ;;
            N*|n*) return 1 ;;
        esac

    done
}

if ask "Install for zsh?" Y; then


    if [[ -f ~/.zshrc ]]; then
        if ask "Create a backup of .zshrc?" Y; then
            cp -i ~/.zshrc ~/.zshrc.bak_kdb
        fi
    fi

cat <<HERE >>~/.zshrc
### generated by kdb install-sh-completion
fpath=(~/.zsh-comp $fpath)
autoload -U compinit && compinit
zmodload -i zsh/complist
### end of generated by kdb install-sh-completion
HERE

    if [ ! -d ~/.zsh-comp ]; then
        mkdir ~/.zsh-comp
    fi

cat << 'HERE' >~/.zsh-comp/_kdb
@CONTENT_OF_ZSH_COMP@
HERE



    echo "installed zsh completion configuration"
fi


if ask "Install for bash?" Y; then
    if [[ -f ~/.bashrc ]]; then
        if ask "Create a backup of .bashrc?" Y; then
            cp -i ~/.bashrc ~/.bashrc.bak_kdb
        fi
    fi

cat << 'HERE' >>~/.bashrc
### generated by kdb install-sh-completion
@CONTENT_OF_BASH_COMP@
### end of generated by kdb install-sh-completion
HERE
    echo "installed bash completion configuration"
fi

