#!/bin/sh

PROMPTCMD="${PROMPTCMD:-"dmenu"}"
MENUCMD="${MENUCMD:-"xmenu"}"
TERMCMD="${TERMCMD:-"xterm"}"
EDITOR="${EDITOR:-"${VISUAL:-"vi"}"}"

term() {
	"$TERMCMD" -e "$@"
}

dialog() {
	term /bin/sh -c '
		cmd="$1"
		shift 1
		printf "\t%s\n" "$@"
		case "$cmd" in
		("cp")
			printf "Copy? [y/N] "
			;;
		("mv")
			printf "Move? [y/N] "
			;;
		("ln")
			printf "Link? [y/N] "
			;;
		("rm")
			printf "Send to trash? [y/N] "
			;;
		esac
		read -r arg
		case "$arg" in
		([Yy]*)      ;;
		(*)     exit ;;
		esac
		case "$cmd" in
		("cp")
			cp -v "$@" .
			;;
		("mv")
			mv -v "$@" .
			;;
		("ln")
			ln -s "$@" .
			;;
		("rm")
			trash "$@"
			;;
		esac
	' xfilesctl "$@"
}

snarf() {
	case "$#" in
	(0)
		# no file to copy
		return
		;;
	esac
	# send URIs to clipboard
	printf 'file://%s\r\n' "$@" |\
	xclip -selection clipboard -in -target "text/uri-list" &
}

paste() {
	cmd="$1"
	shift 1
	{
		# get URIs from clipboard
		xclip -selection clipboard -out -target "text/uri-list"
		echo
	} | sed 's,^file://,,' | tr -d '\r' | {
		set --
		while read -r f
		do
			case "$f" in
			("")
				;;
			(*)
				set -- "$@" "$f"
				;;
			esac
		done
		dialog "$cmd" "$@"
	}
}

dropmenu() {
	case "$(
	"$MENUCMD" <<-EOF
		copy
		move
		link
		none
	EOF
	)" in
	("copy")
		dialog "cp" "$@"
		;;
	("move")
		dialog "mv" "$@"
		;;
	("link")
		dialog "ln" "$@"
		;;
	("term")
		"$TERMCMD" &
		;;
	esac
}

dirmenu() {
	case "$(
	"$MENUCMD" <<-EOF
		copy
		move
		link
		term
	EOF
	)" in
	("copy")
		paste "cp" "$@"
		;;
	("move")
		paste "mv" "$@"
		;;
	("link")
		paste "ln" "$@"
		;;
	("term")
		"$TERMCMD" &
		;;
	esac
}

filemenu() {
	case "$(
	"$MENUCMD" <<-EOF
		rename
		snarf
		trash
		edit
	EOF
	)" in
	("rename")
		term bulkrename "$@"
		;;
	("snarf")
		snarf "$@"
		;;
	("trash")
		dialog "rm" "$@"
		;;
	("edit")
		"$TERMCMD" -e "$EDITOR" "$1" &
		;;
	esac
}

changedir() {
	xprop -id "$WINDOWID" -format "_CONTROL_GOTO" 8u -set "_CONTROL_GOTO" "$1"
}

operation="$1"
shift 1
case "$operation" in
("menu")
	case "$#" in
	(0)
		dirmenu "$@"
		;;
	(*)
		filemenu "$@"
		;;
	esac
	;;
("drop-ask")
	dropmenu "$@"
	;;
("drop-copy")
	dialog "cp" "$@"
	;;
("drop-move")
	dialog "mv" "$@"
	;;
("drop-link")
	dialog "ln" "$@"
	;;
(^BackSpace)
	# go up
	changedir ".."
	;;
(^F5|^[Rr])
	# cd to where we are just to refresh
	changedir "."
	;;
(^[LlGg])
	# call dmenu to go somewhere
	newdir="$("$PROMPTCMD" -w "$WINDOWID" </dev/null)" && \
	changedir "$newdir"
	;;
(^[Cc])
	# snarf files
	snarf "$@"
	;;
(^[Vv])
	# copy snarfed files
	paste "cp"
	;;
(^Delete)
	case "$#" in
	(0)
		# nothing to delete
		;;
	(*)
		dialog "rm" "$@"
		;;
	esac
	;;
esac

exit
