#!/usr/bin/env bash
set -x
sudo apt install -y powerline grip pandoc texlive-xetex texlive-latex-base texlive-fonts-recommended lmodern virtualenv yarn  #vim-airline vim-airline-themes

DEST=${1:-/etc/skel}sudo apt-get install -y clang jsonlint bear ccls vim-ale shellcheck



# Jupyter - prepare jupyter virtualenv for jupyter-vim
sudo apt-get install -y jupyter jupyter-core

set pyxversion=3

# downgrading jupyter-client to fix ''Exception 'coroutine' object is not subscriptable'
virtualenv -p /usr/bin/python3 ${DEST}/jupyter_virtualenv && \
	source ${DEST}/jupyter_virtualenv/bin/activate; pip3 install jupyter && \
	pip3 install -Iv jupyter_client==6.1.12 \
	deactivate

if [[ ! -d "${DEST}/.jupyter" ]]; then
jupyter-console --generate-config
fi
#jupyter-qtconsole --generate-config

JUPYTER_CONFIG=${DEST}/.jupyter/jupyter_console_config.py

# For console
sed -i '/^# c.ZMQTerminalInteractiveShell.include_other_output =.*/ s/.*/&\nc.ZMQTerminalInteractiveShell.include_other_output = True/' ${JUPYTER_CONFIG}

#For qtconsole (qt not installed in the virtualenv use when using system jupyter-core jupyter-qtconsole)
#JUPYTER_CONFIG=${DEST}/.jupyter/jupyter_qtconsole_config.py
#sed -i '/^# c.ConsoleWidget.include_other_output =.*/ s/.*/&\nc.ConsoleWidget.include_other_output = True/' ${JUPYTER_CONFIG}

# ale supported programs
sudo apt install -y isort mypy pycodestyle pydocstyle python3-pyflakes python3-pylama python3-pylint-flask python3-pylint-django python3-pylint-common python3-pylint-celery  
#prospector

sudo sed -i -e 's/"syntax on/syntax on/' /etc/vim/vimrc
sudo sed -i -e 's/"set background=dark/set background=dark/' /etc/vim/vimrc

# Macros

# Directories for swap, backup and undo
mkdir -p ${DEST}/.vim/swap
mkdir -p ${DEST}/.vim/backup
mkdir -p ${HOME}/.vim/undo

# Format json
cat > ${DEST}/.vimrc << 'EOF'

" Format json
nmap =j  :%!python -m json.tool<CR>
EOF

# vimrc additions
cat > ${DEST}/.vimrc << 'EOF'

" enable syntax highlighting
syntax enable

" persistant undo file in a single location
set undodir=${HOME}/.vim/undo// " Maintain undo history between sessions
set undofile

" Put backup files in a single location with timestamped names
"set backupdir=${HOME}/.vim/backup//
"au BufWritePre * let &bex = substitute(expand('%:p:h'), '/', ':', 'g') . strftime(';%FT%T')
set nobackup

" Put swap files in a single location
set directory=${HOME}/.vim/swap//

" enable mouse
set mouse=a

set encoding=utf-8

" Show file options above the command line
set wildmenu

" Don't offer to open certain files/directories
set wildignore+=*.bmp,*.gif,*.ico,*.jpg,*.png,*.ico
set wildignore+=*.pdf,*.psd
set wildignore+=node_modules/*,bower_components/*

" `gf` opens file under cursor in a new vertical split
nnoremap gf :vertical wincmd f<CR>"

" Display tabs at the beginning of a line in Python mode as bad.
au BufRead, BufNewFile *.py,*.pyw match BadWhitespace /^\t\+/

" Make trailing whitespace be flagged as bad.
au BufRead, BufNewFile *.py,*.pyw,*.c,*.h match BadWhitespace /\s\+$/

" Use the below highlight group when displaying bad whitespace is desired.
highlight BadWhitespace ctermbg=red guibg=red

" add the proper PEP8 indentation
au BufNewFile, BufRead *.py
    \ set tabstop=4
    \ set softtabstop=4
    \ set shiftwidth=4
    \ set textwidth=79
    \ set expandtab
    \ set autoindent
    \ set fileformat=unix

" show a visual line under the cursor's current line
set cursorline

" show the matching part of the pair for [] {} and ()
set showmatch

" enable all Python syntax highlighting features
let python_highlight_all = 1
syntax on

" Shortcut to rapidly toggle `set list`
nmap <leader>l :set list!<CR>

" Use the same symbols as TextMate for tabstops and EOLs
set listchars=tab:▸\ ,eol:¬

" tmux will only forward escape sequences to the terminal if surrounded by a DCS sequence
" http://sourceforge.net/mailarchive/forum.php?thread_name=AANLkTinkbdoZ8eNR1X2UobLTeww1jFrvfJxTMfKSq-L%2B%40mail.gmail.com&forum_name=tmux-users
 
if exists('$TMUX')
  let &t_SI = "\<Esc>Ptmux;\<Esc>\<Esc>]50;CursorShape=1\x7\<Esc>\\"
  let &t_EI = "\<Esc>Ptmux;\<Esc>\<Esc>]50;CursorShape=0\x7\<Esc>\\"
else
  let &t_SI = "\<Esc>]50;CursorShape=1\x7"
  let &t_EI = "\<Esc>]50;CursorShape=0\x7"
endif
EOF

# Xresources-hybrid-reduced-contrast
cat > ${DEST}/.Xresources << 'EOF'
! Hybrid Terminal Colours. Uses the palette from Tomorrow-Night:
! http://github.com/chriskempson/tomorrow-theme/blob/master/vim/colors/Tomorrow-Night.vim
! and the reduced contrast background color from Codecademy's online editor:
! https://www.codecademy.com/learn
! vim: ft=xdefaults

*background: #232C31
*foreground: #C5C8C6
! black
*color0: #2D3C46
*color8: #425059
! red
*color1: #A54242
*color9: #CC6666
! green
*color2: #8C9440
*color10: #B5BD68
! yellow
*color3: #DE935F
*color11: #F0C674
! blue
*color4: #5F819D
*color12: #81A2BE
! magenta
*color5: #85678F
*color13: #B294BB
! cyan
*color6: #5E8D87
*color14: #8ABEB7
! white
*color7: #6C7A80
*color15: #C5C8C6
EOF

cd ${DEST} || exit
sudo apt install  -y git

# a vi plugin that doesn't install with Vundle
git clone https://github.com/joe-skb7/cscope-maps.git ${DEST}vim/bundle/cscope-maps

git clone http://github.com/VundleVim/Vundle.vim.git ${DEST}/.vim/bundle/Vundle.vim


# Prepend to the .vimrc
if [ -f ${DEST}/.vimrc_pending ];then
	rm ${DEST}/.vimrc_pending
fi
touch ${DEST}/.vimrc_pending

cat > $DEST/.vimrc_pending <<-EOF
	set nocompatible              " be iMproved, required
	filetype off                  " required

	set clipboard=unnamed
	set relativenumber
	set number

	" set the runtime path to include Vundle and initialize
	set rtp+=$HOME/.vim/bundle/Vundle.vim
	call vundle#begin()
	" alternatively, pass a path where Vundle should install plugins
	"call vundle#begin('$HOME/some/path/here')

	" let Vundle manage Vundle, required
	Plugin 'VundleVim/Vundle.vim'

	" plugin on GitHub repos
	Plugin 'joonty/vdebug'
	Plugin 'voldikss/vim-floaterm'
	Plugin 'tpope/vim-fugitive'
	Plugin 'jreybert/vimagit'
	Plugin 'wincent/command-t'
	Plugin 'tmhedberg/SimpylFold'
	Plugin 'vim-scripts/indentpython.vim'
	"Plugin 'Valloric/YouCompleteMe'
	Plugin 'nvie/vim-flake8'
	Plugin 'jupyter-vim/jupyter-vim'
	Plugin 'jnurmine/Zenburn'
	Plugin 'w0ng/vim-hybrid'
	Plugin 'altercation/vim-colors-solarized'
	"Plugin 'kien/ctrlp.vim'
	Plugin 'ctrlpvim/ctrlp.vim'
	Plugin 'liuchengxu/vim-which-key'
	"Plugin 'Lokaltog/powerline', {'rtp': 'powerline/bindings/vim/'}
	Plugin 'vim-airline/vim-airline'
	Plugin 'vim-airline/vim-airline-themes'
	Plugin 'will133/vim-dirdiff'
	Plugin 'jiangmiao/auto-pairs'
	Plugin 'mhinz/vim-startify'
	"Plugin 'mhinz/vim-signify'
	Plugin 'airblade/vim-gitgutter'
	Plugin 'airblade/vim-rooter'
	Plugin 'terryma/vim-multiple-cursors'
	Plugin 'sudar/vim-arduino-syntax'
	Plugin 'ekalinin/Dockerfile.vim'
	Plugin 'mattboehm/vim-unstack'
	Plugin 'edkolev/tmuxline.vim'
	Plugin 'tmux-plugins/vim-tmux'
	Plugin 'christoomey/vim-tmux-navigator'

    " ai supported coding
    " After installation and configuration, you will need to authenticate by running 
    " :Codeium Auth, copying the token from your browser and pasting it into API token request.
    Plugin 'Exafunction/codeium.vim'
    set statusline+=\{…\}%3{codeium#GetStatusString()}

	" C related
	" cscope key mapping: https://github.com/joe-skb7/cscope-maps/blob/master/plugin/cscope_maps.vim#L52
	"Plugin 'joe-skb7/cscope-map'  " See git clone above 
	Plugin 'bogado/file-line'
	Plugin 'rickhowe/diffchar.vim'

	" vim-snipmate
	Plugin 'MarcWeber/vim-addon-mw-utils'
	Plugin 'tomtom/tlib_vim'
	Plugin 'garbas/vim-snipmate'
	let g:snipMate = { 'snippet_version' : 1 }

	" Optional:
	Plugin 'honza/vim-snippets'

	" requires tmux.conf setting: set -g focus-events on or tmux-plugins/tmux-sensible plugin.
	Plugin 'tmux-plugins/vim-tmux-focus-events'

	" text objects - http://github.com/kana/vim-textobj-user/wiki
	Plugin 'kana/vim-textobj-user'
	Plugin 'bps/vim-textobj-python'

	" toggleable panels
	Plugin 'tpope/vim-vinegar'
	Plugin 'vim-scripts/taglist.vim'
	Plugin 'majutsushi/tagbar'
	Plugin 'preservim/nerdtree'
	Plugin 'ryanoasis/vim-devicons'
	Plugin 'tiagofumo/vim-nerdtree-syntax-highlight'
	Plugin 'tsony-tsonev/nerdtree-git-plugin'
	Plugin 'jistr/vim-nerdtree-tabs'
	Plugin 'severin-lemaignan/vim-minimap'

	nmap <F8> :TagbarToggle<CR>

	" Indent guides"
	Plugin 'preservim/vim-indent-guides'
	let g:indent_guides_enable_on_vim_startup = 1


	" Always use the same virtualenv for vim, regardless of what Python
	" environment is loaded in the shell from which vim is launched
	let g:vim_virtualenv_path = "${HOME}/jupyter_virtualenv/"
	if exists('g:vim_virtualenv_path')
	    pythonx import os; import vim
	    pythonx activate_this = os.path.join(vim.eval("g:vim_virtualenv_path"), 'bin/activate_this.py')
	    pythonx with open(activate_this) as f: exec(f.read(), {'__file__': activate_this})
	endif

	let g:NERDTreeGitStatusWithFlags = 1
	let g:NERDTreeIndicatorMapCustom = {
	    \ "Modified"  : "✹",
	    \ "Staged"    : "✚",
	    \ "Untracked" : "✭",
	    \ "Renamed"   : "➜",
	    \ "Unmerged"  : "═",
	    \ "Deleted"   : "✖",
	    \ "Dirty"     : "✗",
	    \ "Clean"     : "✔︎",
	    \ 'Ignored'   : '☒',
	    \ "Unknown"   : "?"
	    \ }

	let g:minimap_highlight='Visual'

	let NERDTreeQuitOnOpen=1

	let NERDTreeMinimalUI = 1

	let NERDTreeDirArrows = 1

	" Nerdtree toggle keymap
	nmap \ :NERDTreeToggle<CR>

	" Nerdtree find keymap
	nnoremap <C-\> :NERDTreeFind<CR>:vertical<CR>

	let g:NERDTreeMapActivateNode="<F3>"
	let g:NERDTreeMapPreview="<F4>"

	" Stop NERDTree from starting automatically
	let g:NERDTreeHijackNetrw=0

	" Start NERDTree when Vim starts with a directory argument.
	autocmd StdinReadPre * let s:std_in=1
	autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists('s:std_in') |
	    \ execute 'NERDTree' argv()[0] | wincmd p | enew | execute 'cd '.argv()[0] | endif

	" Exit Vim if NERDTree is the only window left.
	autocmd BufEnter * if tabpagenr('$') == 1 && winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() |
	    \ quit | endif

	" 80 characters line
	set colorcolumn=81
	"execute "set colorcolumn=" . join(range(81,335), ',')
	highlight ColorColumn ctermbg=Black ctermfg=DarkRed

	" Highlight trailing spaces
	" http://vim.wikia.com/wiki/Highlight_unwanted_spaces
	highlight ExtraWhitespace ctermbg=red guibg=red
	match ExtraWhitespace /\s\+$/
	autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
	autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
	autocmd InsertLeave * match ExtraWhitespace /\s\+$/
	autocmd BufWinLeave * call clearmatches()

	Plugin 'godlygeek/tabular'
	Plugin 'plasticboy/vim-markdown'

	Plugin 'iamcco/markdown-preview.nvim'

	let vim_markdown_preview_github=1
	"let vim_markdown_preview_pandoc=1
	let vim_markdown_preview_toggle=1
	let vim_markdown_preview_hotkey='<c-m>'

	Plugin 'saltstack/salt-vim'
	Plugin 'fatih/vim-go'

	" CtrlP
	let g:ctrlp_map = '<c-p>'
	let g:ctrlp_cmd = 'CtrlP'

	" Python
	Plugin 'hynek/vim-python-pep8-indent'
	Plugin 'jmcantrell/vim-virtualenv'
	Plugin 'fisadev/vim-isort'	 " Automatically sort python imports
	" Python mode (indentation, doc, refactor, lints, code checking, motion and
	" operators, highlighting, run and ipdb breakpoints)
	Plugin 'python-mode/python-mode'
	Plugin 'vim-syntastic/syntastic'
	Plugin 'preservim/nerdcommenter'
	Plugin 'sbdchd/neoformat'

	" flutter/dart
	Plugin 'dart-lang/dart-vim-plugin'
	Plugin 'natebosch/vim-lsc'
	Plugin 'natebosch/vim-lsc-dart'

	let g:lsc_auto_map = v:true

	Plugin 'thosakwe/vim-flutter'

	" Some of these key choices were arbitrary;
	" it's just an example.
	"nnoremap <leader>fa :FlutterRun<cr>
	"nnoremap <leader>fq :FlutterQuit<cr>
	"nnoremap <leader>fr :FlutterHotReload<cr>
	"nnoremap <leader>fR :FlutterHotRestart<cr>
	"nnoremap <leader>fD :FlutterVisualDebug<cr>

	" COC intellisense engine  http://github.com/neoclide/coc.nvim/wiki/Install-coc.nvim
	Plugin 'neoclide/coc.nvim'
	Plugin 'tjdevries/coc-zsh'

	" Neomake is a plugin for Vim/Neovim to asynchronously run programs.
	Plugin 'neomake/neomake'
	Plugin 'coddingtonbear/neomake-platformio'
	Plugin 'maralla/completor.vim'

	" Asynchronous Lint Engine - syntax checking and semantic errors
	Plugin 'dense-analysis/ale'

	let g:ale_linters = { 'cpp': ['clangd'] }
	let g:ale_fixers = { 'cpp': [ 'clang-format' ] }
	let g:ale_python_executable='python3'

	let g:ale_python_flake8_executable = 'python3'
	let g:ale_python_flake8_options = '-m flake8'

	" Disable ale lsp so that coc is used
	let g:ale_disable_lsp = 1

	" Rust
	Plugin 'rust-lang/rust.vim'

	Plugin 'luochen1990/rainbow'
	let g:rainbow_active = 1 "0 if you want to enable it later via :RainbowToggle

	" VSCode like remote container development plugin to support devcontainer.json
	" based spawning and development in docker containers.
	Plugin 'jamestthompson3/nvim-remote-containers'

	" FZF 
	set rtp+=~/.fzf
	Plugin 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all'  }

	" All of your Plugins must be added before the following line
	call vundle#end()            " required
	filetype plugin indent on    " required
	filetype plugin on
	set foldenable 
	set foldmethod=marker
	au FileType sh let g:sh_fold_enabled=5
	au FileType sh let g:is_bash=1
	au FileType sh set foldmethod=syntax
	au FileType zsh set foldmethod=syntax
	.

	set pyxversion=3

	"---------------------------------------
	" Flutter menu for vim
	"call FlutterMenu()

	"---------------------------------------
	" Syntastic

	" show list of errors and warnings on the current file
	nmap <leader>e :Errors<CR>
	" turn to next or previous errors, after open errors list
	nmap <leader>n :lnext<CR>
	nmap <leader>p :lprevious<CR>

	set statusline+=%#warningmsg#
	set statusline+=%{SyntasticStatuslineFlag()}
	set statusline+=%*

	" check also when just opened the file
	let g:syntastic_check_on_open = 1
	let g:syntastic_always_populate_loc_list = 1
	let g:syntastic_auto_loc_list = 1
	let g:syntastic_enable_signs = 1

	" syntastic checker for javascript.
	" eslint is the only tool support JSX.
	" If you don't need write JSX, you can use jshint.
	" And eslint is slow, but not a hindrance
	let g:syntastic_javascript_checkers = ['jshint']
	" let g:syntastic_javascript_checkers = ['eslint']

	" syntastic checker for python.
	" let g:syntastic_python_checkers = ["pylint"]
	" let g:syntastic_python_checkers = ["flake8"]
	let g:syntastic_python_checkers = ['prospector']

	" don't put icons on the sign column (it hides the vcs status icons of signify)
	let g:syntastic_enable_signs = 1

	" custom icons (enable them if you use a patched font, and enable the previous 
	" setting)
	let g:syntastic_error_symbol = '✗'
	let g:syntastic_warning_symbol = '⚠'
	let g:syntastic_style_error_symbol = '✗'
	let g:syntastic_style_warning_symbol = '⚠'
	"----------------------------------------

	if has('gui_running')
	  set background=dark
	  silent! colorscheme hybrid
	else
	  let g:hybrid_custom_term_colors = 1
	  let g:hybrid_reduced_contrast = 1 " Remove this line if using the default palette.
	  silent! colorscheme hybrid
	endif

	silent! call togglebg#map("<F5>")

	" Airline customizations
	let g:airline#extensions#tabline#enabled = 1
	let g:airline_powerline_fonts = 1




	" Nerdcommenter customizations
	" Add spaces after comment delimiters by default
	let g:NERDSpaceDelims = 1

	" Use compact syntax for prettified multi-line comments
	let g:NERDCompactSexyComs = 1

	" Align line-wise comment delimiters flush left instead of following code indentation
	let g:NERDDefaultAlign = 'left'

	" Set a language to use its alternate delimiters by default
	let g:NERDAltDelims_java = 1

	" Use one space after # comment character in python,
	" see http://tinyurl.com/y4hm29o3
	let g:NERDAltDelims_python = 1

	" Add your own custom formats or override the defaults
	let g:NERDCustomDelimiters = { 'c': { 'left': '/**','right': '*/' } }

	" Allow commenting and inverting empty lines (useful when commenting a region)
	let g:NERDCommentEmptyLines = 1

	" Enable trimming of trailing whitespace when uncommenting
	let g:NERDTrimTrailingWhitespace = 1

	" Nerdtree customizations
	" hide .pyc files
	let NERDTreeIgnore=['\.pyc$', '\~$']

	" Nerdtree toggle keymap
	nmap \ :NERDTreeToggle<CR> 

	" Nerdtree find keymap
	nnoremap <C-\> :NERDTreeFind<CR>:vertical<CR>

	" Python docstrings for folded code.
	let g:SimpylFold_docstring_preview=1

	" Flag unnecessary whitespace
	au BufRead, BufNewFile *.py,*.pyw,*.c,*.h match BadWhitespace /\s\+$/lib

	" toggle between all lines folded and no lines folded.
	:nnoremap <expr> <f2> &foldlevel ? 'zM' :'zR'

EOF

# append the existing vimrc to the plugin additions
cat ${DEST}/.vimrc >> ${DEST}/.vimrc_pending

# copy it back to the vimrc
cp ${DEST}/.vimrc_pending ${DEST}/.vimrc	
#mv ${DEST}/.vimrc_pending ${DEST}/.vimrc	

# Install Vundle plugins
HOME=${DEST}; vim -V -E -s -c "source ${DEST}/.vimrc" -c "PluginInstall" -c "PluginUpdate" -c "qa!"

# Install Coc plugins FIXME
HOME=${DEST}; vim -V -E -s -c "source ${DEST}/.vimrc" -c "CocInstall coc-java coc-go coc-python coc-flutter coc-css coc-cssmodules coc-xml coc-json coc-yaml coc-html coc-git coc-docker coc-snippets coc-pairs coc-eslint coc-json coc-prettier coc-tsserver coc-react-refactor" -c "qa!" 

HOME=${DEST}; vim -V -E -s /tmp/tempdir <<-EOF
	:source ${DEST}/.vimrc
        :call coc#util#install()
	:CocStart
	:CocInstall coc-java coc-go coc-python coc-flutter coc-css coc-cssmodules coc-xml coc-json coc-yaml coc-html coc-git coc-docker coc-snippets coc-pairs coc-eslint coc-json coc-prettier coc-tsserver coc-react-refactor
	:qa!
EOF

xmap <leader>a  <Plug>(coc-codeaction-selected)
nmap <leader>a  <Plug>(coc-codeaction-selected)

# Add platformio support to Coc. See: 
# http://github.com/MaskRay/ccls/wiki/coc.nvim 
# http://github.com/neoclide/coc.nvim/blob/101175f47c15ff11eb599c617ef895f578f758b8/doc/coc.txt
# Configuration is stored at:
# `$HOME/.vim/coc-settings.json` or
# `$HOME/.config/nvim/coc-settings.json` by default)
# or the /etc/skel equivalent which we can edit with jq

# Create a Makefile file in the project directory
HOME=${DEST} vim -V -E -s /tmp/Makefile.platformio_example <<-EOF
	# Uncomment lines below if you have problems with $PATH
	#SHELL := /bin/bash
	#PATH := /usr/local/bin:$(PATH)

	all:
					platformio run

	upload:
					platformio run --target upload

	clean:
					platformio run --target clean

	program:
					platformio run --target program

	uploadfs:
					platformio run --target uploadfs

	update:
					platformio update
EOF

sudo apt-get install -y ccls jq

# Initialize a project with platformio
#
# pio init --ide vim 
#
# in the root folder of the project. This command generates a .ccls file which can be read by ccls.

#To build the project in vim, simply call :Neomake! any compilation errors will appear in vim.

# Editing the coc-settings.json, a jsonc file format that supports comments, using jq 
# /etc/skel/.vim/bundle/coc.nvim/.vim/coc-settings.json
# /home/default/.vim/coc-settings.json
# 

# :CocConfig
#{
#    "languageserver": {
#      "golang": {
#        "command": "gopls",
#        "rootPatterns": ["go.mod", ".vim/", ".git/", ".hg/"],
#        "filetypes": ["go"],
#        "initializationOptions": {
#          "usePlaceholders": true
#        }
#{
#{
#    "languageserver":{
#     "ccls": {
#        "enable": false,
#        "command": "ccls",
#        "filetypes": ["c", "cpp", "cuda", "objc", "objcpp"],
#        "rootPatterns": [".ccls", "compile_commands.json", ".vim/", ".git/", ".hg/"],
#        "initializationOptions": {
#		"cache": {
#                	"directory": "/tmp/ccls"
#		},
#	"client": {
#		"snippetSupport": true
#	}		
#        }
#    }
#}

## Configure coc-vim to play nicely with clangd
#{
#  "languageserver": {
#    "clangd": {
#      "command": "clangd",
#      "args": ["--background-index"],
#      "rootPatterns": [
#        "compile_flags.txt",
#        "compile_commands.json",
#        ".vim/",
#        ".git/",
#        ".hg/"
#      ],
#      "filetypes": ["c", "cpp", "objc", "objcpp"]
#    }
#  },
#  "diagnostic.displayByAle": true
#}


declare -A COC_OPT
COC_OPT[0]='. .languageserver |= .+ {"clangd":{ "command":"clangd", "args":["--background-index"], rootPatterns:["compile_flags.txt", "compile_commands.json", ".vim/", ".git/", ".hg/"], filetypes:["c", "cpp", "objc", "objcpp"]}}'
COC_OPT[1]='. .languageserver |= .+ {"golang":{ "command":"gopls", "rootpatterns":["go.mod", ".vim/", ".git/", "hg/"],"filetypes":["go"], "initializationOptions":{"usePlaceholders":true}}}' 
COC_OPT[2]='. .languageserver |= .+ {"ccls":{ "command":"ccls", rootPatterns:[".ccls", "compile_commands.json", ".vim/", ".git/", ".hg/"], filetypes:["c", "cpp", "cuda", "objc", "objcpp"], "initializationOptions":{"cache":{"directory":"/tmp/ccls"},"client":{"snippetSupport":true}}}}'
COC_OPT[3]='.["diagnostic.displayByAle"] = "true"'


for ((i = 0; i < ${#COC_OPT[@]}; ++i)); do
	OPTION="${COC_OPT[$i]}"
	jq "${OPTION}" ${DEST}/.vim/coc-settings.json > /tmp/coc-settings.json.new && \
		mv -b /tmp/coc-settings.json.new ${DEST}/.vim/coc-settings.json
done

cd "${HOME}"/.vim/bundle/coc.nvim || return
yarn install
yarn build

mkdir -p ${HOME}/.config/coc

# Install YouCompleteMe support
sudo apt install -y build-essential cmake universal-ctags
sudo apt install -y python3-dev python3-dev

# semantic support for C-family
#cd $HOME/.vim/bundle/YouCompleteMe/ && ./install.py --clang-completer

# Python should work automatically 
#cd $HOME/.vim/bundle/YouCompleteMe/ && ./install.py

# Go support -
#cd $HOME/.vim/bundle/YouCompleteMe/ && ./install.py --gocode-code --clang-completer 

# dodgy - searches for dodgy looking lines in Python code
# python3-pylint-celery - Pylint plugin for code using the Celery library (Python3)
# python3-pylint-django - Pylint plugin for analysing code using Django (Python 3)
# python3-pylint-flask - pip install pylint-flask - Pylint plugin for analysing code when using Flask
# python3-pylint-plugin-utils - Utilities and helpers for writing Pylint plugins (Python 3)
# python3-requirements-detector - finds and lists the requirements of a Python project
# python3-setoptconf - retrieve Python3 program settings from a variety of sources

