#!/bin/sh

# Simple script to setup my dotfiles.

# ----

DOT="https://github.com/yamagi/dotfiles.git"
VIM="https://github.com/yamagi/vimrc.git"

# ----

# Do we have git?
command -v git >/dev/null 2>&1

if [ $? -ne 0 ] ; then
	echo "git is not installed."
	exit 1
fi

# Make sure that we're in our $HOME.
cd $HOME

# Cleanup crap from previous runs.
if [ -e dotfiles ] ; then
	rm -Rf dotfiles
fi

# Mkay, depending on user we're doing
# complete or partial installs. 
if [ $(whoami) != "root" ] ; then
	echo "Running as user, doing a full install."

	if [ -e .dotfiles ] ; then
		if [ ! -d .dotfiles ] ; then
			echo "~/.dotfiles is already there and not a directory."
			exit 1
		fi

		echo "Dotfiles already installed, updating."

		git --work-tree=${HOME} --git-dir=${HOME}/.dotfiles fetch

		if [ $? -ne 0 ] ; then
			echo "git fetch failed."
			exit 1
		fi

		git --work-tree=${HOME} --git-dir=${HOME}/.dotfiles reset --hard origin/master
	else
		if [ -e .dotfiles ] ; then
			if [ ! -d .dotfiles ] ; then
				echo "~/.dotfiles is already there and not a directory."
				exit 1
			fi
		fi

		echo "Installing dotfiles."

		git clone $DOT

		if [ $? -ne 0 ] ; then
			echo "git clone failed."
			exit 1
		fi

		mv dotfiles/.git .dotfiles
		. dotfiles/.zsh/config/aliases.zsh
		git --work-tree=${HOME} --git-dir=${HOME}/.dotfiles checkout .
		git --work-tree=${HOME} --git-dir=${HOME}/.dotfiles config status.showuntrackedfiles no

		rm -Rf dotfiles
	fi
else
	echo "Running as root, doing a partial install / upgrade."

	if [ -e .dotfiles ] ; then 
		if [ -d .dotfiles ] ; then
			echo "Full installation found, bailing out."
			exit 1
		fi
	else
		git clone $DOT

		mkdir -p .config

		cp dotfiles/.profile .
		cp dotfiles/.shrc .

		cp dotfiles/.zlogin .
		cp dotfiles/.zlogout .
		cp dotfiles/.zshrc .

		if [ -d .zsh ] ; then
			rm -Rf .zsh/config
			rm -Rf .zsh/completions

			cp -r dotfiles/.zsh/config .zsh
			cp -r dotfiles/.zsh/completions .zsh
		else
			if [ -e .zsh ] ; then
				rm -Rf .zsh
			fi

			cp -r dotfiles/.zsh .
		fi

		if [ -e .config/tmux ] ; then
			rm -Rf .config/tmux
		fi

		cp -r dotfiles/.config/tmux .config/tmux

		rm -Rf dotfiles
	fi
fi

# Vim is the same for all users.
if [ -e .vim ] ; then
	if [ ! -d .vim ] ; then
		echo "~/.vim is already there and not a directory."
		exit 1
	fi

	echo "Vim already installed, updating."

	git --work-tree=${HOME}/.vim --git-dir=${HOME}/.vim/.git fetch

	if [ $? -ne 0 ] ; then
		echo "git fetch failed."
		exit 1
	fi

	git --work-tree=${HOME}/.vim --git-dir=${HOME}/.vim/.git reset --hard origin/master
else
	echo "Installing Vim."

	git clone $VIM .vim

	if [ $? -ne 0 ] ; then
		echo "git clone failed."
		exit 1
	fi
fi

if [ -e .vimrc ] ; then
	rm .vimrc
fi

echo "Everything's okay. Have fun."
