#!/bin/sh
# narrow symlinker to match stow, but only from ~/.dotfiles

# todo: this doesn't deal well in replacing files that are currently in stow-created directories
# (IE, migration from stow -> stowo, if stow created the outline)

default_packages=$(ls "$HOME/.dotfiles/" | grep -vE "(os|readme.org|theming|bootstrap|LICENSE)" | tr $'\n' ' ')

if [ -z "$*" ]; then
    cat<<EOF
give me something to stOwO:
$(ls "$HOME/.dotfiles/")

or use the keyword 'all' to install:
$default_packages

EOF
    exit 1
fi

if [ "$*" = "all" ]; then
    set -- $default_packages
fi

while [ ! -z "$1" ]; do
    package=$1
    if ! cd "$HOME/.dotfiles/$1"; then
	echo "Package failed '${1}', aborting"
	shift
	continue
    fi

    # find . -type f | while read -r path; do
    results=$(
    git ls-files | while read -r path; do
	target="${HOME}/${path}"
	target=$(echo "$target" | sed 's#/\./#/#')

	# match symlink style of vanilla stow
	path="$(pwd)/${path}"
	path=$(echo "$path" | sed 's#/\./#/#')
	path=$(echo "$path" | sed "s#$HOME/##")

	# hell yeah brother HH
	prepend=$(echo "$path" | tr -dc '/' | cut -c3- | sed 's#/#../#g')

	# todo?: os -> prefix

	# remove one level (os packages are nested a level)
	# note: somehow using a case statement breaks here
	if echo "$package" | grep -q 'os/'; then
	    prepend=$(echo "$prepend" | cut -c4-)
	fi

	path="$prepend$path"

	mkdir -p "$(dirname "$target")"

	if readlink "$target" >/dev/null; then
	    if [ "$(readlink "$target")" = "$path" ]; then
		# echo "link already in place, skipping $path"
		continue
	    else
		echo "updating link $path"
	    fi

	    rm "$target"
	fi

	if [ -f "$target" ]; then
	    if [ -z "$BS" ]; then
		echo "skipping conflict: $target (set BS=t to override)"
		continue
	    fi

	    rm "$target"
	fi

	echo ln -s "$path" "$target"
	ln -s "$path" "$target"
    done
    )

    if [ ! -z "$results" ]; then
	echo "stOwOing $1"
	pwd
	echo "$results"
	echo
    fi

    shift
done
