#!/bin/sh

## Set up some variables
name="$(basename "$0" .sh)"
deps="git rsync mktemp basename"

logfile="${PWD}/${name}.log"
tempfolder="$(mktemp -d)"
gitdir="$PWD/.dotfiles"
homedir="$PWD"
repo='git@gitlab.com:rehashedsalt/home.git'

## Define some functions
log() {
	[ -z ${1+x} ] && return 1
	printf "\e[94m${name}\e[0m: $1\n"
}

validatedep() {
	if ! which $1 > /dev/null 2>&1; then
		return 1
	fi
	return 0
}

## Do the do
# Rotate the logfile, if necessary
if [ -f "$logfile" ]; then
	log "Found old logfile. Rotating"
	mv "$logfile" "$logfile.old"
fi
# Ensure we have the proper dependencies
log "Validating dependencies"
for dep in $deps; do
	if ! validatedep "$dep"; then
		log "Could not find critical dependency \"$dep\""
		exit 1
	fi
done

# Build Home folder skeleton
log "Building skeleton folder layout"
mkdir Desktop Documents Downloads Games Music Pictures Projects ROMs System Videos

# Clone the dotfiles
log "Cloning repository"
git clone --recursive --depth 100 --separate-git-dir="$gitdir" "$repo" "$tempfolder" >> "$logfile" 2>&1
error="$?"
if ! [ "$error" -eq "0" ]; then
	log "Failed cloning repository \"$repo\": git returned $error"
	log "See $logfile for details"
	log "Do you have the appropriate permissions? Does the remote host know your key?"
	exit 2
fi
# Move them to where they should be
log "Moving cloned repo from \"$tempfolder\" into \"$homedir\""
rsync -rvl --exclude ".git" "$tempfolder/" "$homedir/" >> "$logfile"
rm -rf "$tempfolder"
rmdir "$tempfolder"
# Finish syncing
log "Updating submodules and performing basic configuration"
git --git-dir="$gitdir" --work-tree="$homedir" submodule update --init --recursive --remote >> "$logfile" 2>&1
git --git-dir="$gitdir" --work-tree="$homedir" submodule foreach 'git checkout master && git pull' >> "$logfile" 2>&1
git --git-dir="$gitdir" --work-tree="$homedir" config status.showUntrackedFiles no >> "$logfile" 2>&1

# Print some post-install instructions
log "Dotfiles set up successfully"
log "Be sure and configure the following before issuing any commits:"
log "    git config --global user.email"
log "    git config --global user.name"
log "You may now delete the script"
exit 0