#!/bin/zsh
# dotfiles installer
# usage: ./install.zsh [dotfiles_dir]

dotdir="${1:-$HOME/dotfiles}"

files=(.zshrc .vimrc .tmux.conf .gitconfig)
dirs=(.zsh .vim/plugin .tmux .local/bin .local/share/fonts)

# backup and symlink files
for f in "${files[@]}"; do
  src="$dotdir/$f"
  dst="$HOME/$f"
  [ ! -f "$src" ] && continue
  if [ -e "$dst" ] && [ ! -L "$dst" ]; then
    mv "$dst" "${dst}.bak"
    echo "backup: $dst -> ${dst}.bak"
  fi
  ln -sf "$src" "$dst"
  echo "link: $dst -> $src"
done

# symlink directories
for d in "${dirs[@]}"; do
  src="$dotdir/.${d#.}"
  dst="$HOME/.${d#.}"
  # handle nested dirs
  if [[ "$d" == */* ]]; then
    src="$dotdir/$d"
    dst="$HOME/$d"
    mkdir -p "$(dirname "$dst")"
  else
    src="$dotdir/$d"
    dst="$HOME/$d"
  fi
  [ ! -d "$src" ] && continue
  if [ -d "$dst" ] && [ ! -L "$dst" ]; then
    mv "$dst" "${dst}.bak"
    echo "backup: $dst -> ${dst}.bak"
  fi
  ln -sf "$src" "$dst"
  echo "link: $dst -> $src"
done

# create vim undo dir
mkdir -p "$HOME/.vim/undo"

# install vim-plug
if [ ! -f "$HOME/.vim/autoload/plug.vim" ]; then
  curl -fLo "$HOME/.vim/autoload/plug.vim" --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
  echo "vim-plug: installed"
  vim +PlugInstall +qall 2>/dev/null
  echo "vim plugins: installed"
fi

# install font (mac only)
if [ "$(uname)" = "Darwin" ] && [ -f "$dotdir/.local/share/fonts/aifont.ttf" ]; then
  cp -f "$dotdir/.local/share/fonts/aifont.ttf" ~/Library/Fonts/aifont.ttf
  echo "font: aifont.ttf -> ~/Library/Fonts/"
fi

echo "done"
