#!/bin/bash

# dependencies check
deps=(git rsync)
not_installed=$(command -V ${deps[@]} 2>&1 | awk -F': +' '$NF == "not found" {printf "%s ", $(NF-1)}')
[[ -n ${not_installed} ]] && echo "Please install missing dependencies: ${not_installed}" 1>&2 && exit 1

git clone --bare https://github.com/imrancio/.cfg.git $HOME/.cfg
function cfg {
  /usr/bin/git --git-dir=$HOME/.cfg/ --work-tree=$HOME $@
}
backup=~/.cfg-backup.$(date +%s)
mkdir $backup

cfg checkout
if [ $? = 0 ]; then
  echo "Checked out cfg."
else
  echo "Backing up pre-existing dot files."
  [[ ! -f ~/README.md ]] || rm -rf ~/README.md
  cfg checkout 2>&1 | egrep "\s+\." | awk {'print $1'} | xargs -I{} rsync -axuv --prune-empty-dirs --remove-source-files {} $backup/{}
fi
cfg checkout
cfg config status.showUntrackedFiles no
