mkdir -p mods-bisect/

blacklist='(openloader|jei|libx|cofh_core|codechickenlib)'

if [ "$1" = 'remove' ]; then
	ls_command='ls mods/*.jar'
	mv_command='mv {} mods-bisect/'
elif [ "$1" = 'return' ]; then
	ls_command='ls mods-bisect/*.jar'
	mv_command='mv {} mods/'
else
	echo "Usage: ./bisect.sh [remove|return] [upper|lower] <amount>"
	exit 1
fi

if [ -n "$3" ]; then
	move_count="$3"
else
	move_count="$(eval "$ls_command" | wc --lines)"
	move_count="$((move_count / 2))"
fi

if [ "$2" = 'upper' ]; then
	filter_command="head -n$move_count"
elif [ "$2" = 'lower' ]; then
	filter_command="tail -n$move_count"
else
	echo "Usage: ./bisect.sh [remove|return] [upper|lower] <amount>"
	exit 1
fi

eval "$ls_command" \
	| grep -E --invert-match --ignore-case "$blacklist" \
	| eval "$filter_command" \
	| xargs --verbose --delimiter='\n' -I '{}' \
		$mv_command

printf 'Moved %s files' "$move_count"
