# -*- shell-script -*-

################################################################################

bashrun_remote="$bashrun_data_home/$bashrun_mode-remote"
bashrun_remote_interface=""

################################################################################

function §remote.run {

    declare -a words
    local cwd action command

    if [[ -f "$bashrun_remote" ]]; then
	
	mapfile -t words < "$bashrun_remote"
	cwd="${words[0]}"
	action="${words[1]}"
	command="${words[@]:2}"

	§debug "action" -v "$action" "command" -v "$command" "cwd" -v "$cwd"

	if §actions.seek "$action"; then
	    cd "$cwd"
	    §engine.action "$action" 0 "$command"	
	    cd - &>/dev/null
	fi

	# we need to force a redisplay of the prompt
        # since readline didn't get an accept-line:
	if ! §cygwin?; then
	    # cygwin will interpret WINCH as USR1 (?)
	    kill -WINCH $$
	fi

	# remove command file
	/bin/rm "$bashrun_remote"

    else
	§debug warn "no command pending in" -v "$bashrun_remote"
	return 1
    fi
}

function §remote.interface.bind {

    local bindings="$bashrun_cache_home/remote-bindings.bash"

    local type="$1"
    local action="$2"
    local keymap="$3"
    local char="$4"
    local keyseq="$5"
    local saved="$(§action.get_name)"
    local remote="0"

    §actions.seek "$action"
    remote="$(§action.get_remote)"
    §actions.seek "$saved"

    [[ remote -eq 0 ]] && return

    if [[ "$type" == "internal" ]]; then
	printf '%s\n' \
	    "bind -m $keymap -x \$'\"\C-z\\x$char\": §bashrun-remote-trap $action'" \
	    >> "$bindings"

    elif [[ "$type" == "requested" ]]; then
	if [[ "$action" == "run" ]]; then
	    [[ "$keyseq" == '\C-m' ]] && keyseq='\e\C-m' 
	    [[ "$keyseq" == '\C-j' ]] && keyseq='\e\C-j' 
	fi
	if [[ "$action" == "term-run" ]]; then
	    [[ "$keyseq" == '\e\C-m' ]] && keyseq='\et'
	fi       

	printf '%s\n' \
	    "bind -m $keymap '\"$keyseq\"':$'\"\C-z\x$char\201\"'" \
	    >> "$bindings"
    fi
}

function §remote.interface.add {
    bashrun_remote_interface+="$@"
    bashrun_remote_interface+=$'\n'
}

function §remote.interface.create {
    local interface="$bashrun_cache_home/remote.bash"
    local bindings="$bashrun_cache_home/remote-bindings.bash"
    local bookmarks="$bashrun_cache_home/remote-bookmarks.bash"

    /bin/cp "$bashrun_site/interface" "$interface"
    printf '%s\n' "$bashrun_remote_interface" >> "$interface"

    printf '%s\n' "source $bindings" >> "$interface"
    printf '%s\n' "source $bookmarks" >> "$interface"
}
