#!/usr/bin/env bash

# invoke this script from your projects root directory

CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# pass "undo" as a script arg to undo most of the setup actions
UNDO_SETUP="$1"
undo() {
	[ "$UNDO_SETUP" == "undo" ]
}

restore() {
	local file="$1"
	rm -f "$file"
	git checkout -- "$file" 2>/dev/null
}

gitignore() {
	local file="$1"
	grep -q "^${file}$" .gitignore 2>/dev/null || echo "$file" >> .gitignore
}

remove_from_gitignore() {
	local file="$1"
	local escaped_filename="$(echo "$file" | sed "s,/,\\\/,g")"
	sed -i"" "/^${escaped_filename}$/d" .gitignore
}

add_files_to_gitignore() {
	if ! undo; then
		gitignore "run_tests"
		gitignore "tests/run_tests_in_isolation"
		gitignore "tests/helpers/helpers.sh"
	else
		remove_from_gitignore "run_tests"
		remove_from_gitignore "tests/run_tests_in_isolation"
		remove_from_gitignore "tests/helpers/helpers.sh"
	fi
}

symlink_user_test_runner() {
	local file="run_tests"
	if ! undo; then
		ln -sf "lib/tmux-test/${file}" "$file"
	else
		restore "$file"
	fi
}

create_directory_for_tests() {
	if ! undo; then
		mkdir -p tests/helpers/
	fi
}

symlink_internal_test_runner() {
	local file="tests/run_tests_in_isolation"
	if ! undo; then
		ln -sf "../lib/tmux-test/${file}" "$file"
	else
		restore "$file"
	fi
}

symlink_test_helpers() {
	local file="tests/helpers/helpers.sh"
	if ! undo; then
		ln -sf "../../lib/tmux-test/${file}" "$file"
	else
		restore "$file"
	fi
}

copy_travis_yml() {
	local file=".travis.yml"
	if ! undo; then
		cp "lib/tmux-test/${file}" "$file"
	else
		restore "$file"
	fi
}

main() {
	add_files_to_gitignore
	symlink_user_test_runner
	create_directory_for_tests
	symlink_internal_test_runner
	symlink_test_helpers
	copy_travis_yml
}
main

