#! /bin/sh

LINK() {
	limit="$1"
	shift
    
	files=""
	while [ $# -ne 0 ]; do
		case "$1" in
			FROM)
				files="$files$([ "$files" = "" ] || echo; ls -p "$2" | sed "s@^@$2/@")"

				shift
				shift
				;;
			SORT)
				case "$2" in
					ALPHA)
						files="$(echo "$files" | sort -f -k 1,1)"
						;;
					TIME)
						files="$(echo "$files" | while read -r file; do
							path="$(echo "$file" | awk '{ print $1 }')"
							eval $(stat -s "$path" 2> /dev/null)
							echo "$st_mtime $file"
						done | sort -k 1,1 | awk '{ $1="" }1')"
						;;
				esac

				shift
				shift
				;;
			REV)
				files="$(echo "$files" | tail -r)"

				shift
				;;
			EXCLUDE)
				files="$(echo "$files" | sed "/$2/d")"

				shift
				shift
				;;
			INCLUDE)
				files="$(echo "$files" | grep -E "$2")"
					
				shift
				shift
				;;
			LABEL)
				case "$2" in
					DATE)
					files="$(echo "$files" | while read -r file; do
						[ "$file" = "" ] && continue
						path="$(echo "$file" | awk '{ print $1 }')"
						eval $(stat -s "$path" 2> /dev/null)
						echo "$file $(date -r $st_mtime '+%Y-%m-%d')"
					done)"
					;;
					TITLE)
					files="$(echo "$files" | while read -r file; do
						[ "$file" = "" ] && continue
						path="$(echo "$file" | awk '{ print $1 }')"
						echo "$file $(head -n1 "$path" 2> /dev/null | sed 's/^#//g' | sed 's/^ //g')"
					done)"
					;;
				esac
				
				shift
				shift
				;;
		esac
	done

	[ "$files" = "" ] && return 0
	[ "$limit" != "ALL" ] && files="$(echo "$files" | head -n$limit)"

	echo "$files" | while read -r file; do
		echo "=> $file"
	done
}