#!/usr/bin/env sh
# Automatically deploys my rice onto a new system

git_url="https://github.com/agryphus/archrice.git"
location="$HOME/repos/dotfiles"

if [ ! -d "$location" ]; then
    mkdir -p "$location"
fi

cd "$location"

if [ "$(git remote get-url origin 2> /dev/null)" != "$git_url" ]; then
    git clone --bare "$git_url" .
fi

alias config="git --git-dir $location --work-tree=$HOME"
config config status.showUntrackedFiles no

# Checkout branch, but move collisions to ~/.config-backup
mkdir -p "$HOME/.config-backup"
config checkout 2>&1 \
    | egrep "\s+\." | awk {'print $1'} \
    | xargs -I {} mv {} "$HOME/.config-backup/"{}

# Fix unsafe permissions on gnupg directory
chmod 700 "$HOME/.local/share/gnupg/"

config submodule init
config submodule update --force --recursive --init --remote

# Git submodules will, by default, have the branch name be a hash
# of the current commit.  This bit just goes into each submodule
# and explicitly checks out master.
cd $HOME
submodules="$(grep submodule .gitmodules | awk -F'"' '{print $2}')"
IFS=$'\n'
for mod_path in $submodules; do
    cd "$HOME/$mod_path"
    git checkout master
done

exec zsh

