#!/bin/sh
BACKUPS_PATH=$HOME/Backups
gitcmd() {
	#First arg should be the name of the subdirectory, second arg should be command
	check_args $# 2
	if [ ! -d "$BACKUPS_PATH/$1" ]; then
		invalid_path_msg "$1"
		return 1;
	fi

	git -C $BACKUPS_PATH/$1 $2
	printf "The command succeded\n"
}

git_clone_backup() {
	check_args $# 2
	git -C $BACKUPS_PATH clone $1:Backups/$2
}

git_clone_proj() {
	check_args $# 2
	git -C $HOME/Projects clone ssh://$1/~/Projects/$2
}

bdiff() {
	check_args $# 2
	if [ ! -d "$BACKUPS_PATH/$1" ]; then
		invalid_path_msg "$1"
		return 1;
	fi
	case "$1" in
		configs) vimdiff "$BACKUPS_PATH/$1/$2" "$XDG_CONFIG_HOME/$2";;
		macros) vimdiff "$BACKUPS_PATH/$1/$2" "$HOME/Macros/$2";;
		global_vim) vimdiff "$BACKUPS_PATH/$1/$2" "/usr/share/vim/$2";;
		*) invalid_path_msg "$1"; return 1;;
	esac
}

overwrite_local() {
	if [ ! -e $BACKUPS_PATH/$1/$2 ]; then
		printf "The backup path $BACKUPS_PATH/$1/$2 does not exist\n"
		return 1;
	fi
	case "$1" in
		configs) cp -r "$BACKUPS_PATH/$1/$2" "$XDG_CONFIG_HOME/";;
		macros) cp -r "$BACKUPS_PATH/$1/$2" "$HOME/Macros/";;
		*) invalid_path_msg "$1"; return 1;;
	esac
	printf "local overwrite successful\n"
}

overwrite_backup() {
	if [ git diff --stat $BACKUPS_PATH/$1 ]; then
		printf "There are uncommited changes in $1\n"
		return 1
	fi
	case "$1" in
		config) cp -r "$XDG_CONFIG_HOME/$2" "$BACKUPS_PATH/$1/$2";;
		macros) cp -r "$HOME/Macros/$2" "$BACKUPS_PATH/$1/$2";;
		*) invalid_path_msg "$1"; return 1;;
	esac
	printf "backup overwrite successful\n"
}

invalid_path_msg() {
	printf "That path is invalid. $@\n"
}

check_args() {
	if [ $1 -ne $2 ]; then
		printf "Invalid number of arguments. Expected $2\n"
		exit;
	fi
	return 0;
}


case "$1" in
	pull-backup)
		case "$2" in 
			configs) pull_backup configs;;
			macros) pull_backup macros;;
		esac
		;;
	overwrite-local) overwrite_local $2 $3;;
	overwrite-backup) overwrite_backup $2 $3;;
	gitcmd) gitcmd "$2" "$3";;
	push-backup) overwrite_backup $2 $3;;
	bclone) git_clone_backup "$2" "$3";;
	pclone) git_clone_proj "$2" "$3";;
	bdiff) bdiff $2 "$3";;
	*) printf "No such option\n";;
esac