#!/bin/bash

[[ -n "$LKP_SRC" ]] || LKP_SRC=$(dirname $(dirname $(readlink -e -v $0)))

source $LKP_SRC/lib/result.sh

shopt -s nullglob

remove_from_mrtts()
{
    local dir=$1
    is_mrt $dir && echo $dir | lkp delete_mrts
}

remove()
{
	local temp_file_unsort=$(mktemp /tmp/lkp-rm-unsort-XXXXXXXXX)
	cleanup_path_record_from_patterns $patterns > $temp_file_unsort || exit

	[[ -s "$temp_file_unsort" ]] ||
	{
		rm -f $temp_file_unsort
		echo "Cannot find the match _result_root according to the patterns: $patterns" >&2
		exit 1
	}

	local temp_file_sort=$(mktemp /tmp/lkp-rm-sort-XXXXXXXXX)
	awk -F'/' '{OFS="/"; NF=NF-2; print}' $temp_file_unsort | sort -u > $temp_file_sort

	local path
	local stale_links

	while read path
	do
		remove_from_mrtts $path
		stale_links="$stale_links $(find $(dirname "$path") -xtype l)"
	done < $temp_file_sort

	cat $temp_file_sort | xargs rm -rf

	rm -vf $stale_links
	rm -f $temp_file_unsort
	rm -f $temp_file_sort
}

usage()
{
	cat >&2 <<-EOF
Usage:
	lkp $script_name <patterns>
Example:
	lkp $script_name /xfstests/ /lkp-ws02/ /v4.3/
EOF
	exit 1
}

script_name=$(basename $0)
[[ $# = 0 ]] && usage

patterns="$*"

temp_file=$(mktemp /tmp/lkp-rm-XXXXXXXXX)
trap "rm -f $temp_file" EXIT

lkp _rt $patterns > $temp_file
[[ -s "$temp_file" ]] || {
	echo "Cannot find the match _result_root according to the patterns: $patterns" >&2
	exit 1
}

_result_root_lines=$(cat $temp_file | wc -l)
echo "The command will remove the following $_result_root_lines _result_root:"

if (( $_result_root_lines > 20 )); then
	 cat $temp_file | head -20
	 echo "..."
else
	cat $temp_file
fi

echo -n "!!! Do you really want to do that? [No/yes]: "
read answer
if [[ $answer = "yes" ]]; then

	remove

	echo "Done" >&2
fi

