#!/usr/bin/env bash
#
# Symlinks ALL the things! (really just all the .dotfile files)

set -e

cd "$(dirname $0)"
export DOTFILES_ROOT="`pwd`"

create_link () {
  ln -s $1 $2
  echo "linked $1 to $2"
}

overwrite_all=false
backup_all=false
skip_all=false

install_file () {
  src=$1
  dest=$2

  if [ -f $dest ] || [ -d $dest ]
  then
    overwrite=false
    backup=false
    skip=false

    if [ "$overwrite_all" == "false" ] && [ "$backup_all" == "false" ] && [ "$skip_all" == "false" ]
    then
      echo "conflict adding $dest"
      echo "[s]kip, [S]kip all, [o]verwrite, [O]verwrite all, [b]ackup, [B]ackup all: "
      echo -n "> "
      read -n 1 cmd
      echo ""

      case "$cmd" in
        o ) overwrite=true;;
        O ) overwrite_all=true;;
        b ) backup=true;;
        B ) backup_all=true;;
        s ) skip=true;;
        S ) skip_all=true;;
        * ) ;;
      esac
    fi

    if [ "$overwrite" == "true" ] || [ "$overwrite_all" == "true" ]
    then
      rm -rf $dest
      echo "removed $dest"
    fi

    if [ "$backup" == "true" ] || [ "$backup_all" == "true" ]
    then
      mv $dest $dest\.bak
      echo "moved $dest to $dest.bak"
    fi

    if [ "$skip" == "true" ] || [ "$skip_all" == "true" ]
    then
      echo "skipped $src"
    else
      create_link $src $dest
    fi
  else
    create_link $src $dest
  fi
}

for src in `find $DOTFILES_ROOT -name \*.dotfile`
do
  dest="$HOME/.`basename \"${src%.*}\"`"
  install_file $src $dest
done

for src in `find $DOTFILES_ROOT -name \*.configdir`
do
  dest="$HOME/.config/`basename \"${src%.*}\"`"
  install_file $src $dest
done

find . -name setup.sh | while read setup; do sh -c "${setup}"; done
