#!/bin/sh
VIMHOME=~/.vim
VIMFILE=~/.vimrc
PWD=$(cd $(dirname $0); pwd)

# function
warn() {
  echo "WARNING: $1" >&2
}
error() {
  echo "ERROR: $1" >&2
  exit 1
}
echo "Installing hightman/vimrc from: $PWD ..."

# backup exists file/dir
echo "Checking to backup old configurations ..."
for f in $VIMHOME $VIMFILE; do
  if [ -e "$f" ]; then
    if [ -e "${f}_bak" ]; then
      rm -rf ${f}_bak || error "Can't remove exists backup file: ${f}_bak"
    fi
    mv $f ${f}_bak || error "Can't rename exists file: $f"  
  fi
done

# link the files
echo "Create symbol links ..."
ln -sf $PWD $VIMHOME
ln -sf $PWD/vimrc $VIMFILE

# init the bundles
echo "Initlize bundles ..."
cd $PWD
mkdir tmp bak
git submodule update --init
vim +BundleInstall! +BundleClean +q +q

# Command-T
if [ -d bundle/command-t/ruby ]; then
	echo "Compilie the plugin: Command-T ..."
	(cd bundle/command-t/ruby/command-t && ruby extconf.rb && make) || warn "Failed to compile Command-T"
fi

# detect env path
echo > vimrc.path
file=vimrc.path
path="/opt/local/bin /usr/local/bin /usr/bin"
util="ctags jsctags phpctags php-cs-fixer xdg-open"
echo "Detecting PATH of binary utils ..."
for e in $util; do
	for p in $path; do
		if [ -x "$p/$e" ]; then
			e2=`echo $e | sed 's#-#_#g'`
			eval "x_$e2=$p/$e"
			break
		fi
	done
done
echo '" Path of Utils' > $file
echo '" Notice: This file generated by install script automatically' >> $file
if [ ! -z "$x_ctags" ]; then
	echo "let g:tagbar_ctags_bin = '$x_ctags'" >> $file
	echo "let g:easytags_cmd = '$x_ctags'" >> $file
fi
if [ ! -z "$x_jsctags" ]; then
	echo "let g:tagbar_type_javascript = {" >> $file
	echo "	\ 'ctagsbin': '$x_jsctags'" >> $file
	echo "\ }" >> $file
fi
if [ ! -z "$x_phpctags" ]; then
	echo "let g:tagbar_phpctags_bin = '$x_phpctags'" >> $file
fi
if [ ! -z "$x_php_cs_fixer" ]; then
	echo "let g:php_cs_fixer_path = '$x_php_cs_fixer'" >> $file
fi
# open online doc:wq
if [ ! -z "$x_xdg_open" ]; then
	echo "let g:jquery_doc_command = '$x_xdg_open'" >> $file
	echo "let g:php_search_doc_command = '$x_xdg_open'" >> $file
fi
if ! grep markdown ~/.ctags > /dev/null 2>&1; then
	cat >> ~/.ctags <<EOT
--langdef=markdown
--langmap=markdown:.mkd.md
--regex-markdown=/^#[ \t]+(.*)/\1/h,Heading_L1/
--regex-markdown=/^##[ \t]+(.*)/\1/i,Heading_L2/
--regex-markdown=/^###[ \t]+(.*)/\1/k,Heading_L3/ ] ] ]
EOT
fi

# xmledit alias for html/xhtml/php
if [ -d "bundle/xmledit" ]; then
	ln -sf $PWD/bundle/xmledit/ftplugin/xml.vim bundle/xmledit/ftplugin/php.vim
	ln -sf $PWD/bundle/xmledit/ftplugin/xml.vim bundle/xmledit/ftplugin/html.vim
	ln -sf $PWD/bundle/xmledit/ftplugin/xml.vim bundle/xmledit/ftplugin/xhtml.vim
fi

echo "VIMRC installed, Enjoy it :-)"

